From e26c0c92bda6a66a5ea2f308b28e53a0a9bfba7f Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 24 May 2023 10:05:15 +1000 Subject: [PATCH 01/15] Inline and remove `numbered_codegen_unit_name`. It is small and has a single call site, and this change will facilitate the next commit. --- .../rustc_monomorphize/src/partitioning/merging.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_monomorphize/src/partitioning/merging.rs b/compiler/rustc_monomorphize/src/partitioning/merging.rs index 5c524a18454ec..9ab8da1858eff 100644 --- a/compiler/rustc_monomorphize/src/partitioning/merging.rs +++ b/compiler/rustc_monomorphize/src/partitioning/merging.rs @@ -98,14 +98,9 @@ pub fn merge_codegen_units<'tcx>( // If we are compiling non-incrementally we just generate simple CGU // names containing an index. for (index, cgu) in codegen_units.iter_mut().enumerate() { - cgu.set_name(numbered_codegen_unit_name(cgu_name_builder, index)); + let numbered_codegen_unit_name = + cgu_name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(index)); + cgu.set_name(numbered_codegen_unit_name); } } } - -fn numbered_codegen_unit_name( - name_builder: &mut CodegenUnitNameBuilder<'_>, - index: usize, -) -> Symbol { - name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(index)) -} From b39b7098eaaf5eb99e2f210ad98307ab310c1eee Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 24 May 2023 10:08:40 +1000 Subject: [PATCH 02/15] Remove the `merging` module. Three of the four methods in `DefaultPartitioning` are defined in `default.rs`. But `merge_codegen_units` is defined in a separate module, `merging`, even though it's less than 100 lines of code and roughly the same size as the other three methods. (Also, the `merging` module currently sits alongside `default`, when it should be a submodule of `default`, adding to the confusion.) In #74275 this explanation was given: > I pulled this out into a separate module since it seemed like we might > want a few different merge algorithms to choose from. But in the three years since there have been no additional merging algorithms, and there is no mechanism for choosing between different merging algorithms. (There is a mechanism, `-Zcgu-partitioning-strategy`, for choosing between different partitioning strategies, but the merging algorithm is just one piece of a partitioning strategy.) This commit merges `merging` into `default`, making the code easier to navigate and read. --- .../src/partitioning/default.rs | 96 +++++++++++++++- .../src/partitioning/merging.rs | 106 ------------------ .../src/partitioning/mod.rs | 1 - 3 files changed, 94 insertions(+), 109 deletions(-) delete mode 100644 compiler/rustc_monomorphize/src/partitioning/merging.rs diff --git a/compiler/rustc_monomorphize/src/partitioning/default.rs b/compiler/rustc_monomorphize/src/partitioning/default.rs index 37b7f6bf8a8fc..60f71f5dd81c4 100644 --- a/compiler/rustc_monomorphize/src/partitioning/default.rs +++ b/compiler/rustc_monomorphize/src/partitioning/default.rs @@ -1,3 +1,4 @@ +use std::cmp; use std::collections::hash_map::Entry; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -14,7 +15,6 @@ use rustc_span::symbol::Symbol; use super::PartitioningCx; use crate::collector::InliningMap; -use crate::partitioning::merging; use crate::partitioning::{ MonoItemPlacement, Partition, PostInliningPartitioning, PreInliningPartitioning, }; @@ -103,7 +103,99 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { cx: &PartitioningCx<'_, 'tcx>, initial_partitioning: &mut PreInliningPartitioning<'tcx>, ) { - merging::merge_codegen_units(cx, initial_partitioning); + assert!(cx.target_cgu_count >= 1); + let codegen_units = &mut initial_partitioning.codegen_units; + + // Note that at this point in time the `codegen_units` here may not be + // in a deterministic order (but we know they're deterministically the + // same set). We want this merging to produce a deterministic ordering + // of codegen units from the input. + // + // Due to basically how we've implemented the merging below (merge the + // two smallest into each other) we're sure to start off with a + // deterministic order (sorted by name). This'll mean that if two cgus + // have the same size the stable sort below will keep everything nice + // and deterministic. + codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str())); + + // This map keeps track of what got merged into what. + let mut cgu_contents: FxHashMap> = + codegen_units.iter().map(|cgu| (cgu.name(), vec![cgu.name()])).collect(); + + // Merge the two smallest codegen units until the target size is + // reached. + while codegen_units.len() > cx.target_cgu_count { + // Sort small cgus to the back + codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate())); + let mut smallest = codegen_units.pop().unwrap(); + let second_smallest = codegen_units.last_mut().unwrap(); + + // Move the mono-items from `smallest` to `second_smallest` + second_smallest.modify_size_estimate(smallest.size_estimate()); + for (k, v) in smallest.items_mut().drain() { + second_smallest.items_mut().insert(k, v); + } + + // Record that `second_smallest` now contains all the stuff that was + // in `smallest` before. + let mut consumed_cgu_names = cgu_contents.remove(&smallest.name()).unwrap(); + cgu_contents.get_mut(&second_smallest.name()).unwrap().append(&mut consumed_cgu_names); + + debug!( + "CodegenUnit {} merged into CodegenUnit {}", + smallest.name(), + second_smallest.name() + ); + } + + let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx); + + if cx.tcx.sess.opts.incremental.is_some() { + // If we are doing incremental compilation, we want CGU names to + // reflect the path of the source level module they correspond to. + // For CGUs that contain the code of multiple modules because of the + // merging done above, we use a concatenation of the names of all + // contained CGUs. + let new_cgu_names: FxHashMap = cgu_contents + .into_iter() + // This `filter` makes sure we only update the name of CGUs that + // were actually modified by merging. + .filter(|(_, cgu_contents)| cgu_contents.len() > 1) + .map(|(current_cgu_name, cgu_contents)| { + let mut cgu_contents: Vec<&str> = + cgu_contents.iter().map(|s| s.as_str()).collect(); + + // Sort the names, so things are deterministic and easy to + // predict. We are sorting primitive `&str`s here so we can + // use unstable sort. + cgu_contents.sort_unstable(); + + (current_cgu_name, cgu_contents.join("--")) + }) + .collect(); + + for cgu in codegen_units.iter_mut() { + if let Some(new_cgu_name) = new_cgu_names.get(&cgu.name()) { + if cx.tcx.sess.opts.unstable_opts.human_readable_cgu_names { + cgu.set_name(Symbol::intern(&new_cgu_name)); + } else { + // If we don't require CGU names to be human-readable, + // we use a fixed length hash of the composite CGU name + // instead. + let new_cgu_name = CodegenUnit::mangle_name(&new_cgu_name); + cgu.set_name(Symbol::intern(&new_cgu_name)); + } + } + } + } else { + // If we are compiling non-incrementally we just generate simple CGU + // names containing an index. + for (index, cgu) in codegen_units.iter_mut().enumerate() { + let numbered_codegen_unit_name = + cgu_name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(index)); + cgu.set_name(numbered_codegen_unit_name); + } + } } fn place_inlined_mono_items( diff --git a/compiler/rustc_monomorphize/src/partitioning/merging.rs b/compiler/rustc_monomorphize/src/partitioning/merging.rs deleted file mode 100644 index 9ab8da1858eff..0000000000000 --- a/compiler/rustc_monomorphize/src/partitioning/merging.rs +++ /dev/null @@ -1,106 +0,0 @@ -use std::cmp; - -use rustc_data_structures::fx::FxHashMap; -use rustc_hir::def_id::LOCAL_CRATE; -use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder}; -use rustc_span::symbol::Symbol; - -use super::PartitioningCx; -use crate::partitioning::PreInliningPartitioning; - -pub fn merge_codegen_units<'tcx>( - cx: &PartitioningCx<'_, 'tcx>, - initial_partitioning: &mut PreInliningPartitioning<'tcx>, -) { - assert!(cx.target_cgu_count >= 1); - let codegen_units = &mut initial_partitioning.codegen_units; - - // Note that at this point in time the `codegen_units` here may not be in a - // deterministic order (but we know they're deterministically the same set). - // We want this merging to produce a deterministic ordering of codegen units - // from the input. - // - // Due to basically how we've implemented the merging below (merge the two - // smallest into each other) we're sure to start off with a deterministic - // order (sorted by name). This'll mean that if two cgus have the same size - // the stable sort below will keep everything nice and deterministic. - codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str())); - - // This map keeps track of what got merged into what. - let mut cgu_contents: FxHashMap> = - codegen_units.iter().map(|cgu| (cgu.name(), vec![cgu.name()])).collect(); - - // Merge the two smallest codegen units until the target size is reached. - while codegen_units.len() > cx.target_cgu_count { - // Sort small cgus to the back - codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate())); - let mut smallest = codegen_units.pop().unwrap(); - let second_smallest = codegen_units.last_mut().unwrap(); - - // Move the mono-items from `smallest` to `second_smallest` - second_smallest.modify_size_estimate(smallest.size_estimate()); - for (k, v) in smallest.items_mut().drain() { - second_smallest.items_mut().insert(k, v); - } - - // Record that `second_smallest` now contains all the stuff that was in - // `smallest` before. - let mut consumed_cgu_names = cgu_contents.remove(&smallest.name()).unwrap(); - cgu_contents.get_mut(&second_smallest.name()).unwrap().append(&mut consumed_cgu_names); - - debug!( - "CodegenUnit {} merged into CodegenUnit {}", - smallest.name(), - second_smallest.name() - ); - } - - let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx); - - if cx.tcx.sess.opts.incremental.is_some() { - // If we are doing incremental compilation, we want CGU names to - // reflect the path of the source level module they correspond to. - // For CGUs that contain the code of multiple modules because of the - // merging done above, we use a concatenation of the names of - // all contained CGUs. - let new_cgu_names: FxHashMap = cgu_contents - .into_iter() - // This `filter` makes sure we only update the name of CGUs that - // were actually modified by merging. - .filter(|(_, cgu_contents)| cgu_contents.len() > 1) - .map(|(current_cgu_name, cgu_contents)| { - let mut cgu_contents: Vec<&str> = cgu_contents.iter().map(|s| s.as_str()).collect(); - - // Sort the names, so things are deterministic and easy to - // predict. - - // We are sorting primitive &strs here so we can use unstable sort - cgu_contents.sort_unstable(); - - (current_cgu_name, cgu_contents.join("--")) - }) - .collect(); - - for cgu in codegen_units.iter_mut() { - if let Some(new_cgu_name) = new_cgu_names.get(&cgu.name()) { - if cx.tcx.sess.opts.unstable_opts.human_readable_cgu_names { - cgu.set_name(Symbol::intern(&new_cgu_name)); - } else { - // If we don't require CGU names to be human-readable, we - // use a fixed length hash of the composite CGU name - // instead. - let new_cgu_name = CodegenUnit::mangle_name(&new_cgu_name); - cgu.set_name(Symbol::intern(&new_cgu_name)); - } - } - } - } else { - // If we are compiling non-incrementally we just generate simple CGU - // names containing an index. - for (index, cgu) in codegen_units.iter_mut().enumerate() { - let numbered_codegen_unit_name = - cgu_name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(index)); - cgu.set_name(numbered_codegen_unit_name); - } - } -} diff --git a/compiler/rustc_monomorphize/src/partitioning/mod.rs b/compiler/rustc_monomorphize/src/partitioning/mod.rs index eafe57a0c0207..8ea82b39534d7 100644 --- a/compiler/rustc_monomorphize/src/partitioning/mod.rs +++ b/compiler/rustc_monomorphize/src/partitioning/mod.rs @@ -93,7 +93,6 @@ //! inlining, even when they are not marked `#[inline]`. mod default; -mod merging; use std::cmp; use std::fs::{self, File}; From 20de2ba7596322026501e1b5134c8724224b844e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 24 May 2023 10:49:48 +1000 Subject: [PATCH 03/15] Remove `{Pre,Post}InliningPartitioning`. I find that these structs obfuscate the code. Removing them and just passing the individual fields around makes the `Partition` method signatures a little longer, but makes the data flow much clearer. E.g. - `codegen_units` is mutable all the way through. - `codegen_units`'s length is changed by `merge_codegen_units`, but only the individual elements are changed by `place_inlined_mono_items` and `internalize_symbols`. - `roots`, `internalization_candidates`, and `mono_item_placements` are all immutable after creation, and all used by just one of the four methods. --- .../src/partitioning/default.rs | 55 ++++------- .../src/partitioning/mod.rs | 96 +++++++++---------- 2 files changed, 64 insertions(+), 87 deletions(-) diff --git a/compiler/rustc_monomorphize/src/partitioning/default.rs b/compiler/rustc_monomorphize/src/partitioning/default.rs index 60f71f5dd81c4..362e21eaecd0a 100644 --- a/compiler/rustc_monomorphize/src/partitioning/default.rs +++ b/compiler/rustc_monomorphize/src/partitioning/default.rs @@ -15,9 +15,7 @@ use rustc_span::symbol::Symbol; use super::PartitioningCx; use crate::collector::InliningMap; -use crate::partitioning::{ - MonoItemPlacement, Partition, PostInliningPartitioning, PreInliningPartitioning, -}; +use crate::partitioning::{MonoItemPlacement, Partition}; pub struct DefaultPartitioning; @@ -26,7 +24,7 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { &mut self, cx: &PartitioningCx<'_, 'tcx>, mono_items: &mut I, - ) -> PreInliningPartitioning<'tcx> + ) -> (Vec>, FxHashSet>, FxHashSet>) where I: Iterator>, { @@ -91,20 +89,15 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { codegen_units.insert(codegen_unit_name, CodegenUnit::new(codegen_unit_name)); } - PreInliningPartitioning { - codegen_units: codegen_units.into_values().collect(), - roots, - internalization_candidates, - } + (codegen_units.into_values().collect(), roots, internalization_candidates) } fn merge_codegen_units( &mut self, cx: &PartitioningCx<'_, 'tcx>, - initial_partitioning: &mut PreInliningPartitioning<'tcx>, + codegen_units: &mut Vec>, ) { assert!(cx.target_cgu_count >= 1); - let codegen_units = &mut initial_partitioning.codegen_units; // Note that at this point in time the `codegen_units` here may not be // in a deterministic order (but we know they're deterministically the @@ -201,20 +194,14 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { fn place_inlined_mono_items( &mut self, cx: &PartitioningCx<'_, 'tcx>, - initial_partitioning: PreInliningPartitioning<'tcx>, - ) -> PostInliningPartitioning<'tcx> { - let mut new_partitioning = Vec::new(); + codegen_units: &mut [CodegenUnit<'tcx>], + roots: FxHashSet>, + ) -> FxHashMap, MonoItemPlacement> { let mut mono_item_placements = FxHashMap::default(); - let PreInliningPartitioning { - codegen_units: initial_cgus, - roots, - internalization_candidates, - } = initial_partitioning; - - let single_codegen_unit = initial_cgus.len() == 1; + let single_codegen_unit = codegen_units.len() == 1; - for old_codegen_unit in initial_cgus { + for old_codegen_unit in codegen_units.iter_mut() { // Collect all items that need to be available in this codegen unit. let mut reachable = FxHashSet::default(); for root in old_codegen_unit.items().keys() { @@ -266,14 +253,10 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { } } - new_partitioning.push(new_codegen_unit); + *old_codegen_unit = new_codegen_unit; } - return PostInliningPartitioning { - codegen_units: new_partitioning, - mono_item_placements, - internalization_candidates, - }; + return mono_item_placements; fn follow_inlining<'tcx>( mono_item: MonoItem<'tcx>, @@ -293,14 +276,16 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { fn internalize_symbols( &mut self, cx: &PartitioningCx<'_, 'tcx>, - partitioning: &mut PostInliningPartitioning<'tcx>, + codegen_units: &mut [CodegenUnit<'tcx>], + mono_item_placements: FxHashMap, MonoItemPlacement>, + internalization_candidates: FxHashSet>, ) { - if partitioning.codegen_units.len() == 1 { + if codegen_units.len() == 1 { // Fast path for when there is only one codegen unit. In this case we // can internalize all candidates, since there is nowhere else they // could be accessed from. - for cgu in &mut partitioning.codegen_units { - for candidate in &partitioning.internalization_candidates { + for cgu in codegen_units { + for candidate in &internalization_candidates { cgu.items_mut().insert(*candidate, (Linkage::Internal, Visibility::Default)); } } @@ -317,15 +302,13 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { } }); - let mono_item_placements = &partitioning.mono_item_placements; - // For each internalization candidates in each codegen unit, check if it is // accessed from outside its defining codegen unit. - for cgu in &mut partitioning.codegen_units { + for cgu in codegen_units { let home_cgu = MonoItemPlacement::SingleCgu { cgu_name: cgu.name() }; for (accessee, linkage_and_visibility) in cgu.items_mut() { - if !partitioning.internalization_candidates.contains(accessee) { + if !internalization_candidates.contains(accessee) { // This item is no candidate for internalizing, so skip it. continue; } diff --git a/compiler/rustc_monomorphize/src/partitioning/mod.rs b/compiler/rustc_monomorphize/src/partitioning/mod.rs index 8ea82b39534d7..dd0a35c4402d3 100644 --- a/compiler/rustc_monomorphize/src/partitioning/mod.rs +++ b/compiler/rustc_monomorphize/src/partitioning/mod.rs @@ -128,7 +128,7 @@ impl<'tcx> Partition<'tcx> for Partitioner { &mut self, cx: &PartitioningCx<'_, 'tcx>, mono_items: &mut I, - ) -> PreInliningPartitioning<'tcx> + ) -> (Vec>, FxHashSet>, FxHashSet>) where I: Iterator>, { @@ -141,12 +141,10 @@ impl<'tcx> Partition<'tcx> for Partitioner { fn merge_codegen_units( &mut self, cx: &PartitioningCx<'_, 'tcx>, - initial_partitioning: &mut PreInliningPartitioning<'tcx>, + codegen_units: &mut Vec>, ) { match self { - Partitioner::Default(partitioner) => { - partitioner.merge_codegen_units(cx, initial_partitioning) - } + Partitioner::Default(partitioner) => partitioner.merge_codegen_units(cx, codegen_units), Partitioner::Unknown => cx.tcx.sess.emit_fatal(UnknownPartitionStrategy), } } @@ -154,11 +152,12 @@ impl<'tcx> Partition<'tcx> for Partitioner { fn place_inlined_mono_items( &mut self, cx: &PartitioningCx<'_, 'tcx>, - initial_partitioning: PreInliningPartitioning<'tcx>, - ) -> PostInliningPartitioning<'tcx> { + codegen_units: &mut [CodegenUnit<'tcx>], + roots: FxHashSet>, + ) -> FxHashMap, MonoItemPlacement> { match self { Partitioner::Default(partitioner) => { - partitioner.place_inlined_mono_items(cx, initial_partitioning) + partitioner.place_inlined_mono_items(cx, codegen_units, roots) } Partitioner::Unknown => cx.tcx.sess.emit_fatal(UnknownPartitionStrategy), } @@ -167,12 +166,17 @@ impl<'tcx> Partition<'tcx> for Partitioner { fn internalize_symbols( &mut self, cx: &PartitioningCx<'_, 'tcx>, - post_inlining_partitioning: &mut PostInliningPartitioning<'tcx>, + codegen_units: &mut [CodegenUnit<'tcx>], + mono_item_placements: FxHashMap, MonoItemPlacement>, + internalization_candidates: FxHashSet>, ) { match self { - Partitioner::Default(partitioner) => { - partitioner.internalize_symbols(cx, post_inlining_partitioning) - } + Partitioner::Default(partitioner) => partitioner.internalize_symbols( + cx, + codegen_units, + mono_item_placements, + internalization_candidates, + ), Partitioner::Unknown => cx.tcx.sess.emit_fatal(UnknownPartitionStrategy), } } @@ -189,26 +193,29 @@ trait Partition<'tcx> { &mut self, cx: &PartitioningCx<'_, 'tcx>, mono_items: &mut I, - ) -> PreInliningPartitioning<'tcx> + ) -> (Vec>, FxHashSet>, FxHashSet>) where I: Iterator>; fn merge_codegen_units( &mut self, cx: &PartitioningCx<'_, 'tcx>, - initial_partitioning: &mut PreInliningPartitioning<'tcx>, + codegen_units: &mut Vec>, ); fn place_inlined_mono_items( &mut self, cx: &PartitioningCx<'_, 'tcx>, - initial_partitioning: PreInliningPartitioning<'tcx>, - ) -> PostInliningPartitioning<'tcx>; + codegen_units: &mut [CodegenUnit<'tcx>], + roots: FxHashSet>, + ) -> FxHashMap, MonoItemPlacement>; fn internalize_symbols( &mut self, cx: &PartitioningCx<'_, 'tcx>, - partitioning: &mut PostInliningPartitioning<'tcx>, + codegen_units: &mut [CodegenUnit<'tcx>], + mono_item_placements: FxHashMap, MonoItemPlacement>, + internalization_candidates: FxHashSet>, ); } @@ -240,44 +247,49 @@ where // In the first step, we place all regular monomorphizations into their // respective 'home' codegen unit. Regular monomorphizations are all // functions and statics defined in the local crate. - let mut initial_partitioning = { + let (mut codegen_units, roots, internalization_candidates) = { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_roots"); partitioner.place_root_mono_items(cx, mono_items) }; - for cgu in &mut initial_partitioning.codegen_units { + for cgu in &mut codegen_units { cgu.create_size_estimate(tcx); } - debug_dump(tcx, "INITIAL PARTITIONING", &initial_partitioning.codegen_units); + debug_dump(tcx, "INITIAL PARTITIONING", &codegen_units); // Merge until we have at most `max_cgu_count` codegen units. { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus"); - partitioner.merge_codegen_units(cx, &mut initial_partitioning); - debug_dump(tcx, "POST MERGING", &initial_partitioning.codegen_units); + partitioner.merge_codegen_units(cx, &mut codegen_units); + debug_dump(tcx, "POST MERGING", &codegen_units); } // In the next step, we use the inlining map to determine which additional // monomorphizations have to go into each codegen unit. These additional // monomorphizations can be drop-glue, functions from external crates, and // local functions the definition of which is marked with `#[inline]`. - let mut post_inlining = { + let mono_item_placements = { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_inline_items"); - partitioner.place_inlined_mono_items(cx, initial_partitioning) + partitioner.place_inlined_mono_items(cx, &mut codegen_units, roots) }; - for cgu in &mut post_inlining.codegen_units { + for cgu in &mut codegen_units { cgu.create_size_estimate(tcx); } - debug_dump(tcx, "POST INLINING", &post_inlining.codegen_units); + debug_dump(tcx, "POST INLINING", &codegen_units); // Next we try to make as many symbols "internal" as possible, so LLVM has // more freedom to optimize. if !tcx.sess.link_dead_code() { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_internalize_symbols"); - partitioner.internalize_symbols(cx, &mut post_inlining); + partitioner.internalize_symbols( + cx, + &mut codegen_units, + mono_item_placements, + internalization_candidates, + ); } let instrument_dead_code = @@ -285,7 +297,7 @@ where if instrument_dead_code { assert!( - post_inlining.codegen_units.len() > 0, + codegen_units.len() > 0, "There must be at least one CGU that code coverage data can be generated in." ); @@ -296,7 +308,7 @@ where // the object file (CGU) containing the dead function stubs is included // in the final binary. This will probably require forcing these // function symbols to be included via `-u` or `/include` linker args. - let mut cgus: Vec<_> = post_inlining.codegen_units.iter_mut().collect(); + let mut cgus: Vec<_> = codegen_units.iter_mut().collect(); cgus.sort_by_key(|cgu| cgu.size_estimate()); let dead_code_cgu = @@ -307,29 +319,17 @@ where } else { // If there are no CGUs that have externally linked items, // then we just pick the first CGU as a fallback. - &mut post_inlining.codegen_units[0] + &mut codegen_units[0] }; dead_code_cgu.make_code_coverage_dead_code_cgu(); } // Finally, sort by codegen unit name, so that we get deterministic results. - let PostInliningPartitioning { - codegen_units: mut result, - mono_item_placements: _, - internalization_candidates: _, - } = post_inlining; + codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str())); - result.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str())); + debug_dump(tcx, "FINAL", &codegen_units); - debug_dump(tcx, "FINAL", &result); - - result -} - -pub struct PreInliningPartitioning<'tcx> { - codegen_units: Vec>, - roots: FxHashSet>, - internalization_candidates: FxHashSet>, + codegen_units } /// For symbol internalization, we need to know whether a symbol/mono-item is @@ -341,12 +341,6 @@ enum MonoItemPlacement { MultipleCgus, } -struct PostInliningPartitioning<'tcx> { - codegen_units: Vec>, - mono_item_placements: FxHashMap, MonoItemPlacement>, - internalization_candidates: FxHashSet>, -} - fn debug_dump<'a, 'tcx: 'a>(tcx: TyCtxt<'tcx>, label: &str, cgus: &[CodegenUnit<'tcx>]) { let dump = move || { use std::fmt::Write; From 59c5259bc92542f76db04cfc96bdb92c4b15401a Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 24 May 2023 11:50:32 +1000 Subject: [PATCH 04/15] Add a clarifying comment. This is something that took me some time to figure out. --- compiler/rustc_monomorphize/src/partitioning/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compiler/rustc_monomorphize/src/partitioning/mod.rs b/compiler/rustc_monomorphize/src/partitioning/mod.rs index dd0a35c4402d3..25c10df18a18c 100644 --- a/compiler/rustc_monomorphize/src/partitioning/mod.rs +++ b/compiler/rustc_monomorphize/src/partitioning/mod.rs @@ -259,6 +259,8 @@ where debug_dump(tcx, "INITIAL PARTITIONING", &codegen_units); // Merge until we have at most `max_cgu_count` codegen units. + // `merge_codegen_units` is responsible for updating the CGU size + // estimates. { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus"); partitioner.merge_codegen_units(cx, &mut codegen_units); From 86754cd8f280657d75b7dbae1845fa2c45ad28a9 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 25 May 2023 14:27:37 +1000 Subject: [PATCH 05/15] Remove some unnecessary `pub` markers. --- compiler/rustc_monomorphize/src/partitioning/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_monomorphize/src/partitioning/mod.rs b/compiler/rustc_monomorphize/src/partitioning/mod.rs index 25c10df18a18c..ac161bc82d911 100644 --- a/compiler/rustc_monomorphize/src/partitioning/mod.rs +++ b/compiler/rustc_monomorphize/src/partitioning/mod.rs @@ -182,7 +182,7 @@ impl<'tcx> Partition<'tcx> for Partitioner { } } -pub struct PartitioningCx<'a, 'tcx> { +struct PartitioningCx<'a, 'tcx> { tcx: TyCtxt<'tcx>, target_cgu_count: usize, inlining_map: &'a InliningMap<'tcx>, @@ -231,7 +231,7 @@ fn get_partitioner(tcx: TyCtxt<'_>) -> Partitioner { } } -pub fn partition<'tcx, I>( +fn partition<'tcx, I>( tcx: TyCtxt<'tcx>, mono_items: &mut I, max_cgu_count: usize, From ed216e2f22896e753f481f40f876e1197c0de43d Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 25 May 2023 14:29:55 +1000 Subject: [PATCH 06/15] Streamline `modify_size_estimate`. --- compiler/rustc_middle/src/mir/mono.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index ff54ec56a29ac..f31b343c94704 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -334,10 +334,7 @@ impl<'tcx> CodegenUnit<'tcx> { } pub fn modify_size_estimate(&mut self, delta: usize) { - assert!(self.size_estimate.is_some()); - if let Some(size_estimate) = self.size_estimate { - self.size_estimate = Some(size_estimate + delta); - } + *self.size_estimate.as_mut().unwrap() += delta; } pub fn contains_item(&self, item: &MonoItem<'tcx>) -> bool { From d816b8b26469db31cef8214a07756c3aa5009d79 Mon Sep 17 00:00:00 2001 From: Brian M Date: Tue, 9 May 2023 00:14:14 -0700 Subject: [PATCH 07/15] Fix Mac Catalyst linking by adding build version Issue #106021 Apple LD requires build versions in object files for Catalyst --- .../rustc_codegen_ssa/src/back/metadata.rs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/compiler/rustc_codegen_ssa/src/back/metadata.rs b/compiler/rustc_codegen_ssa/src/back/metadata.rs index 8bf84772f0869..ad27b854d59a2 100644 --- a/compiler/rustc_codegen_ssa/src/back/metadata.rs +++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs @@ -188,6 +188,11 @@ pub(crate) fn create_object_file(sess: &Session) -> Option { let arch = match sess.target.options.cpu.as_ref() { @@ -258,6 +263,33 @@ pub(crate) fn create_object_file(sess: &Session) -> Option Option { + if !target.llvm_target.ends_with("-macabi") { + return None; + } + /// The `object` crate demands "X.Y.Z encoded in nibbles as xxxx.yy.zz" + /// e.g. minOS 14.0 = 0x000E0000, or SDK 16.2 = 0x00100200 + fn pack_version((major, minor): (u32, u32)) -> u32 { + (major << 16) | (minor << 8) + } + + let platform = object::macho::PLATFORM_MACCATALYST; + let min_os = (14, 0); + let sdk = (16, 2); + + let mut build_version = object::write::MachOBuildVersion::default(); + build_version.platform = platform; + build_version.minos = pack_version(min_os); + build_version.sdk = pack_version(sdk); + Some(build_version) +} + pub enum MetadataPosition { First, Last, From dd56f930cc6e174a24ddd1ea5f1bbf9af978abf9 Mon Sep 17 00:00:00 2001 From: Ziru Niu Date: Thu, 25 May 2023 18:37:58 +0800 Subject: [PATCH 08/15] Clarify safety concern of `io::Read::read` is only relevant in unsafe code --- library/std/src/io/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 9e09ce337bc0e..8a007d095d5e3 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -593,7 +593,8 @@ pub trait Read { /// This may happen for example because fewer bytes are actually available right now /// (e. g. being close to end-of-file) or because read() was interrupted by a signal. /// - /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety. + /// As this trait is safe to implement, callers in unsafe code cannot rely on + /// `n <= buf.len()` for safety. /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes. /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if /// `n > buf.len()`. @@ -603,8 +604,8 @@ pub trait Read { /// contents of `buf` being true. It is recommended that *implementations* /// only write data to `buf` instead of reading its contents. /// - /// Correspondingly, however, *callers* of this method must not assume any guarantees - /// about how the implementation uses `buf`. The trait is safe to implement, + /// Correspondingly, however, *callers* of this method in unsafe code must not assume + /// any guarantees about how the implementation uses `buf`. The trait is safe to implement, /// so it is possible that the code that's supposed to write to the buffer might also read /// from it. It is your responsibility to make sure that `buf` is initialized /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one From dee65a4fa15605ade963a86b562e8f40130e8313 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Fri, 5 May 2023 10:52:02 +0000 Subject: [PATCH 09/15] fix for `Self` not respecting tuple Ctor privacy This fixes #111220 by checking the privacy of tuple constructors using `Self`, so the following code now errors ```rust mod my { pub struct Foo(&'static str); } impl AsRef for my::Foo { fn as_ref(&self) -> &str { let Self(s) = self; // previously compiled, now errors correctly s } } ``` --- compiler/rustc_hir_typeck/messages.ftl | 2 + compiler/rustc_hir_typeck/src/errors.rs | 8 ++++ .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 7 +++ ...111220-2-tuple-struct-fields-projection.rs | 33 +++++++++++++ ...20-2-tuple-struct-fields-projection.stderr | 9 ++++ .../issue-111220-tuple-struct-fields.rs | 46 +++++++++++++++++++ .../issue-111220-tuple-struct-fields.stderr | 21 +++++++++ 7 files changed, 126 insertions(+) create mode 100644 tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.rs create mode 100644 tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.stderr create mode 100644 tests/ui/privacy/issue-111220-tuple-struct-fields.rs create mode 100644 tests/ui/privacy/issue-111220-tuple-struct-fields.stderr diff --git a/compiler/rustc_hir_typeck/messages.ftl b/compiler/rustc_hir_typeck/messages.ftl index 4a669e3f8b8a4..93d3061e9742a 100644 --- a/compiler/rustc_hir_typeck/messages.ftl +++ b/compiler/rustc_hir_typeck/messages.ftl @@ -90,3 +90,5 @@ hir_typeck_candidate_trait_note = `{$trait_name}` defines an item `{$item_name}` [implement] , perhaps you need to implement it *[other] , perhaps you need to restrict type parameter `{$action_or_ty}` with it } + +hir_typeck_ctor_is_private = tuple struct constructor `{$def}` is private diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index 102a313067fd2..e45b8e3d024de 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -319,3 +319,11 @@ pub struct CandidateTraitNote { pub item_name: Ident, pub action_or_ty: String, } + +#[derive(Diagnostic)] +#[diag(hir_typeck_ctor_is_private, code = "E0603")] +pub struct CtorIsPrivate { + #[primary_span] + pub span: Span, + pub def: String, +} diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 9721e3b427d2b..9a97156054cf8 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -1,4 +1,5 @@ use crate::callee::{self, DeferredCallResolution}; +use crate::errors::CtorIsPrivate; use crate::method::{self, MethodCallee, SelfSource}; use crate::rvalue_scopes; use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LocalTy, RawTy}; @@ -1210,6 +1211,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match ty.normalized.ty_adt_def() { Some(adt_def) if adt_def.has_ctor() => { let (ctor_kind, ctor_def_id) = adt_def.non_enum_variant().ctor.unwrap(); + // Check the visibility of the ctor. + let vis = tcx.visibility(ctor_def_id); + if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(), tcx) { + tcx.sess + .emit_err(CtorIsPrivate { span, def: tcx.def_path_str(adt_def.did()) }); + } let new_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); let user_substs = Self::user_substs_for_adt(ty); user_self_ty = user_substs.user_self_ty; diff --git a/tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.rs b/tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.rs new file mode 100644 index 0000000000000..f413b50277861 --- /dev/null +++ b/tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.rs @@ -0,0 +1,33 @@ +mod b { + pub struct A(u32); +} + +trait Id { + type Assoc; +} +impl Id for b::A { + type Assoc = b::A; +} +impl Id for u32 { + type Assoc = u32; +} + + +trait Trait { + fn method(&self) + where + T: Id; +} + +impl Trait for ::Assoc { + fn method(&self) + where + T: Id, + { + let Self(a) = self; + //~^ ERROR: tuple struct constructor `A` is private + println!("{a}"); + } +} + +fn main() {} diff --git a/tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.stderr b/tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.stderr new file mode 100644 index 0000000000000..231a4da8b5f7f --- /dev/null +++ b/tests/ui/privacy/issue-111220-2-tuple-struct-fields-projection.stderr @@ -0,0 +1,9 @@ +error[E0603]: tuple struct constructor `A` is private + --> $DIR/issue-111220-2-tuple-struct-fields-projection.rs:27:13 + | +LL | let Self(a) = self; + | ^^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0603`. diff --git a/tests/ui/privacy/issue-111220-tuple-struct-fields.rs b/tests/ui/privacy/issue-111220-tuple-struct-fields.rs new file mode 100644 index 0000000000000..78d35fd96da3d --- /dev/null +++ b/tests/ui/privacy/issue-111220-tuple-struct-fields.rs @@ -0,0 +1,46 @@ +mod b { + #[derive(Default)] + pub struct A(u32); +} + +impl b::A { + fn inherent_bypass(&self) { + let Self(x) = self; + //~^ ERROR: tuple struct constructor `A` is private + println!("{x}"); + } +} + +pub trait B { + fn f(&self); +} + +impl B for b::A { + fn f(&self) { + let Self(a) = self; + //~^ ERROR: tuple struct constructor `A` is private + println!("{}", a); + } +} + +pub trait Projector { + type P; +} + +impl Projector for () { + type P = b::A; +} + +pub trait Bypass2 { + fn f2(&self); +} + +impl Bypass2 for <() as Projector>::P { + fn f2(&self) { + let Self(a) = self; + //~^ ERROR: tuple struct constructor `A` is private + println!("{}", a); + } +} + +fn main() {} diff --git a/tests/ui/privacy/issue-111220-tuple-struct-fields.stderr b/tests/ui/privacy/issue-111220-tuple-struct-fields.stderr new file mode 100644 index 0000000000000..17a32379cc0a8 --- /dev/null +++ b/tests/ui/privacy/issue-111220-tuple-struct-fields.stderr @@ -0,0 +1,21 @@ +error[E0603]: tuple struct constructor `A` is private + --> $DIR/issue-111220-tuple-struct-fields.rs:8:13 + | +LL | let Self(x) = self; + | ^^^^^^^ + +error[E0603]: tuple struct constructor `A` is private + --> $DIR/issue-111220-tuple-struct-fields.rs:20:13 + | +LL | let Self(a) = self; + | ^^^^^^^ + +error[E0603]: tuple struct constructor `A` is private + --> $DIR/issue-111220-tuple-struct-fields.rs:40:13 + | +LL | let Self(a) = self; + | ^^^^^^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0603`. From 00f9fe43ebe0bde6a0a819581bed3be73a0441d4 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Wed, 17 May 2023 10:30:14 +0000 Subject: [PATCH 10/15] Use translatable diagnostics in `rustc_const_eval` --- compiler/rustc_abi/src/lib.rs | 49 +- .../rustc_codegen_cranelift/src/common.rs | 16 +- compiler/rustc_codegen_gcc/src/consts.rs | 2 +- compiler/rustc_codegen_gcc/src/context.rs | 15 +- compiler/rustc_codegen_llvm/messages.ftl | 6 +- compiler/rustc_codegen_llvm/src/consts.rs | 5 +- compiler/rustc_codegen_llvm/src/context.rs | 17 +- compiler/rustc_codegen_llvm/src/errors.rs | 3 +- .../src/debuginfo/type_names.rs | 3 +- compiler/rustc_const_eval/messages.ftl | 502 ++++++++++++- .../rustc_const_eval/src/const_eval/error.rs | 710 ++++++++++++++---- .../src/const_eval/eval_queries.rs | 97 ++- .../src/const_eval/machine.rs | 37 +- .../rustc_const_eval/src/const_eval/mod.rs | 13 +- compiler/rustc_const_eval/src/errors.rs | 206 ++++- .../rustc_const_eval/src/interpret/cast.rs | 20 +- .../src/interpret/eval_context.rs | 35 +- .../rustc_const_eval/src/interpret/intern.rs | 27 +- .../src/interpret/intrinsics.rs | 75 +- .../rustc_const_eval/src/interpret/memory.rs | 63 +- .../src/interpret/terminator.rs | 51 +- .../src/interpret/validity.rs | 217 +++--- compiler/rustc_const_eval/src/lib.rs | 1 + .../src/transform/check_consts/ops.rs | 133 ++-- compiler/rustc_error_messages/src/lib.rs | 4 + compiler/rustc_errors/messages.ftl | 6 +- compiler/rustc_errors/src/diagnostic.rs | 4 +- compiler/rustc_errors/src/diagnostic_impls.rs | 23 +- .../rustc_hir_analysis/src/check/check.rs | 2 +- .../src/diagnostics/diagnostic_builder.rs | 16 +- .../src/diagnostics/subdiagnostic.rs | 23 +- .../rustc_macros/src/diagnostics/utils.rs | 27 +- compiler/rustc_middle/messages.ftl | 35 + compiler/rustc_middle/src/error.rs | 55 ++ compiler/rustc_middle/src/lib.rs | 3 +- .../src/mir/interpret/allocation.rs | 48 +- .../rustc_middle/src/mir/interpret/error.rs | 422 +++++------ .../rustc_middle/src/mir/interpret/mod.rs | 42 +- .../rustc_middle/src/mir/interpret/value.rs | 3 +- compiler/rustc_middle/src/mir/mod.rs | 90 +-- compiler/rustc_middle/src/mir/pretty.rs | 2 +- compiler/rustc_middle/src/mir/syntax.rs | 3 +- compiler/rustc_middle/src/ty/consts/int.rs | 9 + compiler/rustc_middle/src/ty/layout.rs | 75 +- compiler/rustc_middle/src/ty/vtable.rs | 2 +- .../rustc_mir_transform/src/const_prop.rs | 15 +- .../src/const_prop_lint.rs | 10 +- compiler/rustc_mir_transform/src/errors.rs | 11 +- compiler/rustc_passes/src/layout_test.rs | 9 +- .../src/typeid/typeid_itanium_cxx_abi.rs | 17 +- compiler/rustc_target/src/abi/call/mod.rs | 11 - .../src/traits/object_safety.rs | 2 +- src/tools/clippy/tests/ui/modulo_one.stderr | 6 +- src/tools/miri/src/diagnostics.rs | 66 +- src/tools/miri/src/eval.rs | 5 +- src/tools/miri/src/helpers.rs | 4 +- src/tools/miri/src/lib.rs | 1 + .../tests/fail/intrinsics/copy_overlapping.rs | 2 +- .../fail/intrinsics/copy_overlapping.stderr | 4 +- .../intrinsics/ptr_offset_from_oob.stderr | 4 +- .../session-diagnostic/diagnostic-derive.rs | 4 +- .../diagnostic-derive.stderr | 8 +- .../subdiagnostic-derive.rs | 12 +- .../subdiagnostic-derive.stderr | 14 +- .../generic_const_exprs/issue-80742.stderr | 4 +- tests/ui/const-ptr/forbidden_slices.stderr | 10 +- .../heap/alloc_intrinsic_errors.stderr | 2 +- .../heap/alloc_intrinsic_nontransient_fail.rs | 4 +- .../alloc_intrinsic_nontransient_fail.stderr | 4 +- .../heap/alloc_intrinsic_untyped.rs | 4 +- .../heap/alloc_intrinsic_untyped.stderr | 6 +- .../dealloc_intrinsic_incorrect_layout.stderr | 2 +- .../consts/const-eval/raw-bytes.32bit.stderr | 14 +- .../consts/const-eval/raw-bytes.64bit.stderr | 14 +- .../ui/consts/const-eval/ub-enum.32bit.stderr | 4 +- .../ui/consts/const-eval/ub-enum.64bit.stderr | 4 +- .../ui/consts/const-eval/ub-uninhabit.stderr | 4 +- .../validate_uninhabited_zsts.32bit.stderr | 2 +- .../validate_uninhabited_zsts.64bit.stderr | 2 +- tests/ui/consts/issue-64506.stderr | 2 +- tests/ui/consts/issue-83182.stderr | 4 +- tests/ui/consts/issue-miri-1910.stderr | 4 +- .../consts/miri_unleashed/assoc_const.stderr | 2 +- .../miri_unleashed/raw_mutable_const.rs | 2 +- .../miri_unleashed/raw_mutable_const.stderr | 4 +- .../consts/missing_span_in_backtrace.stderr | 4 +- tests/ui/consts/offset_from_ub.stderr | 14 +- tests/ui/consts/raw-ptr-const.rs | 2 +- tests/ui/consts/raw-ptr-const.stderr | 4 +- .../issue-8460-const.noopt.stderr | 12 +- .../issue-8460-const.opt.stderr | 12 +- ...8460-const.opt_with_overflow_checks.stderr | 12 +- tests/ui/statics/uninhabited-static.stderr | 4 +- 93 files changed, 2459 insertions(+), 1105 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 43db66a3c2869..2ee63c286ba5c 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -209,7 +209,7 @@ pub enum TargetDataLayoutErrors<'a> { InvalidAddressSpace { addr_space: &'a str, cause: &'a str, err: ParseIntError }, InvalidBits { kind: &'a str, bit: &'a str, cause: &'a str, err: ParseIntError }, MissingAlignment { cause: &'a str }, - InvalidAlignment { cause: &'a str, err: String }, + InvalidAlignment { cause: &'a str, err: AlignFromBytesError }, InconsistentTargetArchitecture { dl: &'a str, target: &'a str }, InconsistentTargetPointerWidth { pointer_size: u64, target: u32 }, InvalidBitsSize { err: String }, @@ -640,30 +640,65 @@ impl fmt::Debug for Align { } } +#[derive(Clone, Copy)] +pub enum AlignFromBytesError { + NotPowerOfTwo(u64), + TooLarge(u64), +} + +impl AlignFromBytesError { + pub fn diag_ident(self) -> &'static str { + match self { + Self::NotPowerOfTwo(_) => "not_power_of_two", + Self::TooLarge(_) => "too_large", + } + } + + pub fn align(self) -> u64 { + let (Self::NotPowerOfTwo(align) | Self::TooLarge(align)) = self; + align + } +} + +impl fmt::Debug for AlignFromBytesError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for AlignFromBytesError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AlignFromBytesError::NotPowerOfTwo(align) => write!(f, "`{align}` is not a power of 2"), + AlignFromBytesError::TooLarge(align) => write!(f, "`{align}` is too large"), + } + } +} + impl Align { pub const ONE: Align = Align { pow2: 0 }; pub const MAX: Align = Align { pow2: 29 }; #[inline] - pub fn from_bits(bits: u64) -> Result { + pub fn from_bits(bits: u64) -> Result { Align::from_bytes(Size::from_bits(bits).bytes()) } #[inline] - pub fn from_bytes(align: u64) -> Result { + pub fn from_bytes(align: u64) -> Result { // Treat an alignment of 0 bytes like 1-byte alignment. if align == 0 { return Ok(Align::ONE); } #[cold] - fn not_power_of_2(align: u64) -> String { - format!("`{}` is not a power of 2", align) + fn not_power_of_2(align: u64) -> AlignFromBytesError { + AlignFromBytesError::NotPowerOfTwo(align) } #[cold] - fn too_large(align: u64) -> String { - format!("`{}` is too large", align) + fn too_large(align: u64) -> AlignFromBytesError { + AlignFromBytesError::TooLarge(align) } let tz = align.trailing_zeros(); diff --git a/compiler/rustc_codegen_cranelift/src/common.rs b/compiler/rustc_codegen_cranelift/src/common.rs index ccb3a0c4f27e4..fda63accdeb59 100644 --- a/compiler/rustc_codegen_cranelift/src/common.rs +++ b/compiler/rustc_codegen_cranelift/src/common.rs @@ -6,6 +6,7 @@ use rustc_index::IndexVec; use rustc_middle::ty::layout::{ FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOfHelpers, }; +use rustc_span::source_map::Spanned; use rustc_span::SourceFile; use rustc_target::abi::call::FnAbi; use rustc_target::abi::{Integer, Primitive}; @@ -499,25 +500,16 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> { fn_abi_request: FnAbiRequest<'tcx>, ) -> ! { if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err { - self.0.sess.span_fatal(span, err.to_string()) + self.0.sess.emit_fatal(Spanned { span, node: err }) } else { match fn_abi_request { FnAbiRequest::OfFnPtr { sig, extra_args } => { - span_bug!( - span, - "`fn_abi_of_fn_ptr({}, {:?})` failed: {}", - sig, - extra_args, - err - ); + span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}"); } FnAbiRequest::OfInstance { instance, extra_args } => { span_bug!( span, - "`fn_abi_of_instance({}, {:?})` failed: {}", - instance, - extra_args, - err + "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}" ); } } diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index 792ab8f890d8f..341f37a41640f 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -39,7 +39,7 @@ fn set_global_alignment<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, gv: LValue<'gcc> match Align::from_bits(min) { Ok(min) => align = align.max(min), Err(err) => { - cx.sess().emit_err(InvalidMinimumAlignment { err }); + cx.sess().emit_err(InvalidMinimumAlignment { err: err.to_string() }); } } } diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index 661681bdb50f2..08507e19652b4 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -477,7 +477,7 @@ impl<'gcc, 'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'gcc, 'tcx> { #[inline] fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { if let LayoutError::SizeOverflow(_) = err { - self.sess().emit_fatal(respan(span, err)) + self.sess().emit_fatal(respan(span, err.into_diagnostic())) } else { span_bug!(span, "failed to get layout for `{}`: {}", ty, err) } @@ -499,21 +499,12 @@ impl<'gcc, 'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'gcc, 'tcx> { } else { match fn_abi_request { FnAbiRequest::OfFnPtr { sig, extra_args } => { - span_bug!( - span, - "`fn_abi_of_fn_ptr({}, {:?})` failed: {}", - sig, - extra_args, - err - ); + span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}"); } FnAbiRequest::OfInstance { instance, extra_args } => { span_bug!( span, - "`fn_abi_of_instance({}, {:?})` failed: {}", - instance, - extra_args, - err + "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}" ); } } diff --git a/compiler/rustc_codegen_llvm/messages.ftl b/compiler/rustc_codegen_llvm/messages.ftl index d77634741fb88..29cabe9808ffc 100644 --- a/compiler/rustc_codegen_llvm/messages.ftl +++ b/compiler/rustc_codegen_llvm/messages.ftl @@ -15,7 +15,11 @@ codegen_llvm_symbol_already_defined = symbol `{$symbol_name}` is already defined codegen_llvm_invalid_minimum_alignment = - invalid minimum global alignment: {$err} + invalid minimum global alignment: {$align} is {$err_kind -> + [not_power_of_two] not power of 2 + [too_large] too large + *[other] {""} + }{$err} codegen_llvm_sanitizer_memtag_requires_mte = `-Zsanitizer=memtag` requires `-Ctarget-feature=+mte` diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 940358acde9a2..49acc59d56d30 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -130,7 +130,10 @@ fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: match Align::from_bits(min) { Ok(min) => align = align.max(min), Err(err) => { - cx.sess().emit_err(InvalidMinimumAlignment { err }); + cx.sess().emit_err(InvalidMinimumAlignment { + err_kind: err.diag_ident(), + align: err.align(), + }); } } } diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 83101a85435a0..ca0f771f5b9e4 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -969,9 +969,9 @@ impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> { #[inline] fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { if let LayoutError::SizeOverflow(_) = err { - self.sess().emit_fatal(Spanned { span, node: err }) + self.sess().emit_fatal(Spanned { span, node: err.into_diagnostic() }) } else { - span_bug!(span, "failed to get layout for `{}`: {}", ty, err) + span_bug!(span, "failed to get layout for `{ty}`: {err:?}") } } } @@ -991,21 +991,12 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> { } else { match fn_abi_request { FnAbiRequest::OfFnPtr { sig, extra_args } => { - span_bug!( - span, - "`fn_abi_of_fn_ptr({}, {:?})` failed: {}", - sig, - extra_args, - err - ); + span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",); } FnAbiRequest::OfInstance { instance, extra_args } => { span_bug!( span, - "`fn_abi_of_instance({}, {:?})` failed: {}", - instance, - extra_args, - err + "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}", ); } } diff --git a/compiler/rustc_codegen_llvm/src/errors.rs b/compiler/rustc_codegen_llvm/src/errors.rs index 6a9173ab450a3..87407aefcd931 100644 --- a/compiler/rustc_codegen_llvm/src/errors.rs +++ b/compiler/rustc_codegen_llvm/src/errors.rs @@ -52,7 +52,8 @@ pub(crate) struct SymbolAlreadyDefined<'a> { #[derive(Diagnostic)] #[diag(codegen_llvm_invalid_minimum_alignment)] pub(crate) struct InvalidMinimumAlignment { - pub err: String, + pub err_kind: &'static str, + pub align: u64, } #[derive(Diagnostic)] diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 6297f91341d44..e91f7b86e5ed6 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -93,8 +93,7 @@ fn push_debuginfo_type_name<'tcx>( Err(e) => { // Computing the layout can still fail here, e.g. if the target architecture // cannot represent the type. See https://github.com/rust-lang/rust/issues/94961. - // FIXME: migrate once `rustc_middle::mir::interpret::InterpError` is translatable. - tcx.sess.fatal(format!("{}", e)); + tcx.sess.emit_fatal(e.into_diagnostic()); } } } else { diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index f6751df443f7a..ea93c8a77f40c 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -1,3 +1,12 @@ +const_eval_const_accesses_static = + constant accesses static + +const_eval_modified_global = + modifying a static's initial value from another static's initializer + +const_eval_panic = + the evaluated program panicked at '{$msg}', {$file}:{$line}:{$col} + const_eval_unstable_in_stable = const-stable function cannot use `#[feature({$gate})]` .unstable_sugg = if it is not part of the public API, make this function unstably const @@ -7,7 +16,7 @@ const_eval_thread_local_access = thread-local statics cannot be accessed at compile-time const_eval_static_access = - {$kind}s cannot refer to statics + {const_eval_const_context}s cannot refer to statics .help = consider extracting the value of the `static` to a `const`, and referring to that .teach_note = `static` and `const` variables can refer to other `const` variables. A `const` variable, however, cannot refer to a `static` variable. .teach_help = To fix this, the value can be extracted to a `const` and then used. @@ -24,20 +33,20 @@ const_eval_raw_ptr_comparison = const_eval_panic_non_str = argument to `panic!()` in a const context must have type `&str` const_eval_mut_deref = - mutation through a reference is not allowed in {$kind}s + mutation through a reference is not allowed in {const_eval_const_context}s -const_eval_transient_mut_borrow = mutable references are not allowed in {$kind}s +const_eval_transient_mut_borrow = mutable references are not allowed in {const_eval_const_context}s -const_eval_transient_mut_borrow_raw = raw mutable references are not allowed in {$kind}s +const_eval_transient_mut_borrow_raw = raw mutable references are not allowed in {const_eval_const_context}s const_eval_max_num_nodes_in_const = maximum number of nodes exceeded in constant {$global_const_id} -const_eval_unallowed_fn_pointer_call = function pointer calls are not allowed in {$kind}s +const_eval_unallowed_fn_pointer_call = function pointer calls are not allowed in {const_eval_const_context}s const_eval_unstable_const_fn = `{$def_path}` is not yet stable as a const fn const_eval_unallowed_mutable_refs = - mutable references are not allowed in the final value of {$kind}s + mutable references are not allowed in the final value of {const_eval_const_context}s .teach_note = References in statics and constants may only refer to immutable values. @@ -49,7 +58,7 @@ const_eval_unallowed_mutable_refs = If you really want global mutable state, try using static mut or a global UnsafeCell. const_eval_unallowed_mutable_refs_raw = - raw mutable references are not allowed in the final value of {$kind}s + raw mutable references are not allowed in the final value of {const_eval_const_context}s .teach_note = References in statics and constants may only refer to immutable values. @@ -60,26 +69,29 @@ const_eval_unallowed_mutable_refs_raw = If you really want global mutable state, try using static mut or a global UnsafeCell. +const_eval_unsupported_untyped_pointer = unsupported untyped pointer in constant + .note = memory only reachable via raw pointers is not supported + const_eval_non_const_fmt_macro_call = - cannot call non-const formatting macro in {$kind}s + cannot call non-const formatting macro in {const_eval_const_context}s const_eval_non_const_fn_call = - cannot call non-const fn `{$def_path_str}` in {$kind}s + cannot call non-const fn `{$def_path_str}` in {const_eval_const_context}s const_eval_unallowed_op_in_const_context = {$msg} const_eval_unallowed_heap_allocations = - allocations are not allowed in {$kind}s - .label = allocation not allowed in {$kind}s + allocations are not allowed in {const_eval_const_context}s + .label = allocation not allowed in {const_eval_const_context}s .teach_note = The value of statics and constants must be known at compile time, and they live for the entire lifetime of a program. Creating a boxed value allocates memory on the heap at runtime, and therefore cannot be done at compile time. const_eval_unallowed_inline_asm = - inline assembly is not allowed in {$kind}s + inline assembly is not allowed in {const_eval_const_context}s const_eval_interior_mutable_data_refer = - {$kind}s cannot refer to interior mutable data + {const_eval_const_context}s cannot refer to interior mutable data .label = this borrow of an interior mutable value may end up in the final value .help = to fix this, the value can be extracted to a separate `static` item and then referenced .teach_note = @@ -89,3 +101,467 @@ const_eval_interior_mutable_data_refer = const_eval_interior_mutability_borrow = cannot borrow here, since the borrowed element may contain interior mutability + +const_eval_undefined_behavior = + it is undefined behavior to use this value + +const_eval_undefined_behavior_note = + The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. + +const_eval_nullary_intrinsic_fail = + could not evaluate nullary intrinsic + +const_eval_error = {$error_kind -> + [static] could not evaluate static initializer + [const] evaluation of constant value failed + [const_with_path] evaluation of `{$instance}` failed + *[other] {""} +} + +const_eval_size_overflow = + overflow computing total size of `{$name}` + +const_eval_invalid_dealloc = + deallocating {$alloc_id}, which is {$kind -> + [fn] a function + [vtable] a vtable + [static_mem] static memory + *[other] {""} + } + +const_eval_align_offset_invalid_align = + `align_offset` called with non-power-of-two align: {$target_align} + +const_eval_invalid_align = + align has to be a power of 2 + +const_eval_invalid_align_details = + invalid align passed to `{$name}`: {$align} is {$err_kind -> + [not_power_of_two] not a power of 2 + [too_large] too large + *[other] {""} + } + +const_eval_invalid_transmute = + transmuting from {$src_bytes}-byte type to {$dest_bytes}-byte type: `{$src}` -> `{$dest}` + +const_eval_upcast_mismatch = + upcast on a pointer whose vtable does not match its type + +const_eval_unreachable_unwind = + unwinding past a stack frame that does not allow unwinding + +const_eval_unwind_past_top = + unwinding past the topmost frame of the stack + +const_eval_double_storage_live = + StorageLive on a local that was already live + +const_eval_call_nonzero_intrinsic = + `{$name}` called on 0 + +const_eval_overflow_shift = + overflowing shift by {$val} in `{$name}` + +const_eval_overflow = + overflow executing `{$name}` + +const_eval_different_allocations = + `{$name}` called on pointers into different allocations + +const_eval_unsigned_offset_from_overflow = + `ptr_offset_from_unsigned` called when first pointer has smaller offset than second: {$a_offset} < {$b_offset} + +const_eval_offset_from_underflow = + `{$name}` called when first pointer is too far before second + +const_eval_offset_from_overflow = + `{$name}` called when first pointer is too far ahead of second + +const_eval_assume_false = + `assume` called with `false` + +const_eval_exact_div_has_remainder = + exact_div: {$a} cannot be divided by {$b} without remainder + +const_eval_raw_eq_with_provenance = + `raw_eq` on bytes with provenance + +const_eval_realloc_or_alloc_with_offset = + {$kind -> + [dealloc] deallocating + [realloc] reallocating + *[other] {""} + } {$ptr} which does not point to the beginning of an object + +const_eval_dealloc_immutable = + deallocating immutable allocation {$alloc} + +const_eval_dealloc_kind_mismatch = + deallocating {$alloc}, which is {$alloc_kind} memory, using {$kind} deallocation operation + +const_eval_dealloc_incorrect_layout = + incorrect layout on deallocation: {$alloc} has size {$size} and alignment {$align}, but gave size {$size_found} and alignment {$align_found} + +const_eval_copy_nonoverlapping_overlapping = + `copy_nonoverlapping` called on overlapping ranges + +const_eval_noreturn_asm_returned = + returned from noreturn inline assembly + +const_eval_not_enough_caller_args = + calling a function with fewer arguments than it requires + +const_eval_incompatible_types = + calling a function with argument of type {$callee_ty} passing data of type {$caller_ty} + +const_eval_incompatible_calling_conventions = + calling a function with calling convention {$callee_conv} using calling convention {$caller_conv} + +const_eval_too_many_caller_args = + calling a function with more arguments than it expected + +const_eval_incompatible_return_types = + calling a function with return type {$callee_ty} passing return place of type {$caller_ty} + +const_eval_dyn_star_call_vtable_mismatch = + `dyn*` call on a pointer whose vtable does not match its type + +const_eval_dyn_call_vtable_mismatch = + `dyn` call on a pointer whose vtable does not match its type + +const_eval_dyn_call_not_a_method = + `dyn` call trying to call something that is not a method + +const_eval_non_const_impl = + impl defined here, but it is not `const` + +const_eval_erroneous_constant = + erroneous constant used + +const_eval_frame_note_inner = inside {$where_ -> + [closure] closure + [instance] `{$instance}` + *[other] {""} +} + +const_eval_frame_note = {$times -> + [0] {const_eval_frame_note_inner} + *[other] [... {$times} additional calls {const_eval_frame_note_inner} ...] +} + +const_eval_dangling_ptr_in_final = encountered dangling pointer in final constant + +const_eval_raw_bytes = the raw bytes of the constant (size: {$size}, align: {$align}) {"{"}{$bytes}{"}"} + +const_eval_const_context = {$kind -> + [const] constant + [static] static + [const_fn] constant function + *[other] {""} +} + +const_eval_for_loop_into_iter_non_const = + cannot convert `{$ty}` into an iterator in {const_eval_const_context}s + +const_eval_question_branch_non_const = + `?` cannot determine the branch of `{$ty}` in {const_eval_const_context}s + +const_eval_question_from_residual_non_const = + `?` cannot convert from residual of `{$ty}` in {const_eval_const_context}s + +const_eval_try_block_from_output_non_const = + `try` block cannot convert `{$ty}` to the result in {const_eval_const_context}s + +const_eval_await_non_const = + cannot convert `{$ty}` into a future in {const_eval_const_context}s + +const_eval_operator_non_const = + cannot call non-const operator in {const_eval_const_context}s + +const_eval_closure_non_const = + cannot call non-const closure in {const_eval_const_context}s + +const_eval_closure_fndef_not_const = + function defined here, but it is not `const` + +const_eval_fn_ptr_call = + function pointers need an RFC before allowed to be called in {const_eval_const_context}s + +const_eval_closure_call = + closures need an RFC before allowed to be called in {const_eval_const_context}s + +const_eval_consider_dereferencing = + consider dereferencing here + +const_eval_deref_coercion_non_const = + cannot perform deref coercion on `{$ty}` in {const_eval_const_context}s + .note = attempting to deref into `{$target_ty}` + .target_note = deref defined here + +const_eval_live_drop = + destructor of `{$dropped_ty}` cannot be evaluated at compile-time + .label = the destructor for this type cannot be evaluated in {const_eval_const_context}s + .dropped_at_label = value is dropped here + +const_eval_align_check_failed = accessing memory with alignment {$has}, but alignment {$required} is required + +const_eval_unreachable = entering unreachable code + +const_eval_bounds_check_failed = + indexing out of bounds: the len is {$len} but the index is {$index} + +const_eval_division_by_zero = + dividing by zero + +const_eval_remainder_by_zero = + calculating the remainder with a divisor of zero + +const_eval_division_overflow = + overflow in signed division (dividing MIN by -1) + +const_eval_remainder_overflow = + overflow in signed remainder (dividing MIN by -1) + +const_eval_pointer_arithmetic_overflow = + overflowing in-bounds pointer arithmetic + +const_eval_invalid_meta_slice = + invalid metadata in wide pointer: slice is bigger than largest supported object + +const_eval_invalid_meta = + invalid metadata in wide pointer: total size is bigger than largest supported object + +const_eval_unterminated_c_string = + reading a null-terminated string starting at {$pointer} with no null found before end of allocation + +const_eval_pointer_use_after_free = + pointer to {$allocation} was dereferenced after this allocation got freed + +const_eval_deref_test = dereferencing pointer failed + +const_eval_memory_access_test = memory access failed + +const_eval_pointer_arithmetic_test = out-of-bounds pointer arithmetic + +const_eval_offset_from_test = out-of-bounds `offset_from` + +const_eval_in_bounds_test = out-of-bounds pointer use + +const_eval_zst_pointer_out_of_bounds = + {$bad_pointer_message}: {$alloc_id} has size {$alloc_size}, so pointer at offset {$ptr_offset} is out-of-bounds + +const_eval_pointer_out_of_bounds = + {$bad_pointer_message}: {$alloc_id} has size {$alloc_size}, so pointer to {$ptr_size} {$ptr_size -> + [1] byte + *[many] bytes + } starting at offset {$ptr_offset} is out-of-bounds + +const_eval_dangling_null_pointer = + {$bad_pointer_message}: null pointer is a dangling pointer (it has no provenance) + +const_eval_dangling_int_pointer = + {$bad_pointer_message}: {$pointer} is a dangling pointer (it has no provenance) + +const_eval_alignment_check_failed = + accessing memory with alignment {$has}, but alignment {$required} is required + +const_eval_write_to_read_only = + writing to {$allocation} which is read-only + +const_eval_deref_function_pointer = + accessing {$allocation} which contains a function + +const_eval_deref_vtable_pointer = + accessing {$allocation} which contains a vtable + +const_eval_invalid_bool = + interpreting an invalid 8-bit value as a bool: 0x{$value} + +const_eval_invalid_char = + interpreting an invalid 32-bit value as a char: 0x{$value} + +const_eval_invalid_tag = + enum value has invalid tag: {$tag} + +const_eval_invalid_function_pointer = + using {$pointer} as function pointer but it does not point to a function + +const_eval_invalid_vtable_pointer = + using {$pointer} as vtable pointer but it does not point to a vtable + +const_eval_invalid_str = + this string is not valid UTF-8: {$err} + +const_eval_invalid_uninit_bytes = + reading memory at {$alloc}{$access}, but memory is uninitialized at {$uninit}, and this operation requires initialized memory + +const_eval_invalid_uninit_bytes_unknown = + using uninitialized data, but this operation requires initialized memory + +const_eval_dead_local = + accessing a dead local variable + +const_eval_scalar_size_mismatch = + scalar size mismatch: expected {$target_size} bytes but got {$data_size} bytes instead + +const_eval_uninhabited_enum_variant_written = + writing discriminant of an uninhabited enum + +const_eval_invalid_value = constructing invalid value + +const_eval_invalid_value_with_path = constructing invalid value at {$path} + + +## The `front_matter`s here refer to either `middle_invalid_value` or `middle_invalid_value_with_path`. + +const_eval_box_to_uninhabited = {$front_matter}: encountered a box pointing to uninhabited type {$ty} + +const_eval_ref_to_uninhabited = {$front_matter}: encountered a reference pointing to uninhabited type {$ty} + + +const_eval_box_to_static = {$front_matter}: encountered a box pointing to a static variable in a constant + +const_eval_ref_to_static = {$front_matter}: encountered a reference pointing to a static variable in a constant + + +const_eval_box_to_mut = {$front_matter}: encountered a box pointing to mutable memory in a constant + +const_eval_ref_to_mut = {$front_matter}: encountered a reference pointing to mutable memory in a constant + +const_eval_expected_non_ptr = {$front_matter}: encountered `{$value}`, but expected plain (non-pointer) bytes + +const_eval_mutable_ref_in_const = {$front_matter}: encountered mutable reference in a `const` + +const_eval_null_fn_ptr = {$front_matter}: encountered a null function pointer + +const_eval_never_val = {$front_matter}: encountered a value of the never type `!` + + +const_eval_range_wrapping = less or equal to {$hi}, or greater or equal to {$lo} + +const_eval_range_singular = equal to {$lo} + +const_eval_range_upper = less or equal to {$hi} + +const_eval_range_lower = greater or equal to {$lo} + +const_eval_range = in the range {$lo}..={$hi} + + +const_eval_nullable_ptr_out_of_range = {$front_matter}: encountered a potentially null pointer, but expected something that cannot possibly fail to be {$in_range} + +const_eval_ptr_out_of_range = {$front_matter}: encountered a pointer, but expected something that cannot possibly fail to be {$in_range} + +const_eval_out_of_range = {$front_matter}: encountered {$value}, but expected something {$in_range} + +const_eval_unsafe_cell = {$front_matter}: encountered `UnsafeCell` in a `const` + +const_eval_uninhabited_val = {$front_matter}: encountered a value of uninhabited type `{$ty}` + +const_eval_invalid_enum_tag = {$front_matter}: encountered {$value}, but expected a valid enum tag + +const_eval_uninit_enum_tag = {$front_matter}: encountered uninitialized bytes, but expected a valid enum tag + +const_eval_uninit_str = {$front_matter}: encountered uninitialized data in `str` + +const_eval_uninit_ref = {$front_matter}: encountered uninitialized memory, but expected a reference + +const_eval_uninit_box = {$front_matter}: encountered uninitialized memory, but expected a box + +const_eval_uninit_raw_ptr = {$front_matter}: encountered uninitialized memory, but expected a raw pointer + +const_eval_uninit_init_scalar = {$front_matter}: encountered uninitialized memory, but expected initialized scalar value + +const_eval_uninit_bool = {$front_matter}: encountered uninitialized memory, but expected a boolean + +const_eval_uninit_char = {$front_matter}: encountered uninitialized memory, but expected a unicode scalar value + +const_eval_uninit_float = {$front_matter}: encountered uninitialized memory, but expected a floating point number + +const_eval_uninit_int = {$front_matter}: encountered uninitialized memory, but expected an integer + +const_eval_uninit_fn_ptr = {$front_matter}: encountered uninitialized memory, but expected a function pointer + +const_eval_uninit = {$front_matter}: encountered uninitialized bytes + +const_eval_invalid_vtable_ptr = {$front_matter}: encountered {$value}, but expected a vtable pointer + +const_eval_invalid_ref_slice_meta = {$front_matter}: encountered invalid reference metadata: slice is bigger than largest supported object + +const_eval_invalid_ref_meta = {$front_matter}: encountered invalid reference metadata: total size is bigger than largest supported object + +const_eval_invalid_box_slice_meta = {$front_matter}: encountered invalid box metadata: slice is bigger than largest supported object + +const_eval_invalid_box_meta = {$front_matter}: encountered invalid box metadata: total size is bigger than largest supported object + +const_eval_unaligned_ref = {$front_matter}: encountered an unaligned reference (required {$required_bytes} byte alignment but found {$found_bytes}) + +const_eval_unaligned_box = {$front_matter}: encountered an unaligned box (required {$required_bytes} byte alignment but found {$found_bytes}) + +const_eval_null_ref = {$front_matter}: encountered a null reference + +const_eval_null_box = {$front_matter}: encountered a null box + +const_eval_dangling_ref_no_provenance = {$front_matter}: encountered a dangling reference ({$pointer} has no provenance) + +const_eval_dangling_box_no_provenance = {$front_matter}: encountered a dangling box ({$pointer} has no provenance) + +const_eval_dangling_ref_out_of_bounds = {$front_matter}: encountered a dangling reference (going beyond the bounds of its allocation) + +const_eval_dangling_box_out_of_bounds = {$front_matter}: encountered a dangling box (going beyond the bounds of its allocation) + +const_eval_dangling_ref_use_after_free = {$front_matter}: encountered a dangling reference (use-after-free) + +const_eval_dangling_box_use_after_free = {$front_matter}: encountered a dangling box (use-after-free) + +const_eval_validation_invalid_bool = {$front_matter}: encountered {$value}, but expected a boolean + +const_eval_validation_invalid_char = {$front_matter}: encountered {$value}, but expected a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`) + +const_eval_invalid_fn_ptr = {$front_matter}: encountered {$value}, but expected a function pointer + +const_eval_stack_frame_limit_reached = + reached the configured maximum number of stack frames + +const_eval_step_limit_reached = + exceeded interpreter step limit (see `#[const_eval_limit]`) + +const_eval_memory_exhausted = + tried to allocate more memory than available to compiler + +const_eval_address_space_full = + there are no more free addresses in the address space + +const_eval_partial_pointer_overwrite = + unable to overwrite parts of a pointer in memory at {$ptr} + +const_eval_partial_pointer_copy = + unable to copy parts of a pointer from memory at {$ptr} + +const_eval_ptr_as_bytes_1 = + this code performed an operation that depends on the underlying bytes representing a pointer + +const_eval_ptr_as_bytes_2 = + the absolute address of a pointer is not known at compile-time, so such operations are not supported + +const_eval_read_pointer_as_bytes = + unable to turn pointer into raw bytes + +const_eval_thread_local_static = + cannot access thread local static ({$did}) + +const_eval_read_extern_static = + cannot read from extern static ({$did}) + +const_eval_too_generic = + encountered overly generic constant + +const_eval_already_reported = + an error has already been reported elsewhere (this should not usually be printed) + +const_eval_size_of_unsized = + size_of called on unsized type `{$ty}` + +const_eval_uninit_unsized_local = + unsized local is used while uninitialized diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index c591ff75ab878..a60e62e2ceaea 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -1,17 +1,25 @@ -use std::error::Error; -use std::fmt; +use std::mem; -use rustc_errors::Diagnostic; +use rustc_errors::{ + DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, EmissionGuarantee, Handler, + IntoDiagnostic, IntoDiagnosticArg, +}; +use rustc_middle::mir::interpret::{ + CheckInAllocMsg, ExpectedKind, InvalidMetaKind, InvalidProgramInfo, PointerKind, + ResourceExhaustionInfo, UndefinedBehaviorInfo, UnsupportedOpInfo, ValidationErrorInfo, + ValidationErrorKind, +}; use rustc_middle::mir::AssertKind; -use rustc_middle::query::TyCtxtAt; +use rustc_middle::ty::TyCtxt; use rustc_middle::ty::{layout::LayoutError, ConstInt}; -use rustc_span::{Span, Symbol}; +use rustc_span::source_map::Spanned; +use rustc_span::{ErrorGuaranteed, Span, Symbol}; +use rustc_target::abi::call::AdjustForForeignAbiError; +use rustc_target::abi::{Size, WrappingRange}; use super::InterpCx; -use crate::interpret::{ - struct_error, ErrorHandled, FrameInfo, InterpError, InterpErrorInfo, Machine, MachineStopType, - UnsupportedOpInfo, -}; +use crate::errors::{self, FrameNote}; +use crate::interpret::{ErrorHandled, InterpError, InterpErrorInfo, Machine, MachineStopType}; /// The CTFE machine has some custom error kinds. #[derive(Clone, Debug)] @@ -23,7 +31,35 @@ pub enum ConstEvalErrKind { Abort(String), } -impl MachineStopType for ConstEvalErrKind {} +impl MachineStopType for ConstEvalErrKind { + fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; + use ConstEvalErrKind::*; + match self { + ConstAccessesStatic => const_eval_const_accesses_static, + ModifiedGlobal => const_eval_modified_global, + Panic { .. } => const_eval_panic, + AssertFailure(x) => x.diagnostic_message(), + Abort(msg) => msg.to_string().into(), + } + } + fn add_args( + self: Box, + adder: &mut dyn FnMut(std::borrow::Cow<'static, str>, DiagnosticArgValue<'static>), + ) { + use ConstEvalErrKind::*; + match *self { + ConstAccessesStatic | ModifiedGlobal | Abort(_) => {} + AssertFailure(kind) => kind.add_args(adder), + Panic { msg, line, col, file } => { + adder("msg".into(), msg.into_diagnostic_arg()); + adder("file".into(), file.into_diagnostic_arg()); + adder("line".into(), line.into_diagnostic_arg()); + adder("col".into(), col.into_diagnostic_arg()); + } + } + } +} // The errors become `MachineStop` with plain strings when being raised. // `ConstEvalErr` (in `librustc_middle/mir/interpret/error.rs`) knows to @@ -34,151 +70,545 @@ impl<'tcx> Into> for ConstEvalErrKind { } } -impl fmt::Display for ConstEvalErrKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use self::ConstEvalErrKind::*; - match self { - ConstAccessesStatic => write!(f, "constant accesses static"), - ModifiedGlobal => { - write!(f, "modifying a static's initial value from another static's initializer") +pub fn get_span_and_frames<'tcx, 'mir, M: Machine<'mir, 'tcx>>( + ecx: &InterpCx<'mir, 'tcx, M>, +) -> (Span, Vec) +where + 'tcx: 'mir, +{ + let mut stacktrace = ecx.generate_stacktrace(); + // Filter out `requires_caller_location` frames. + stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*ecx.tcx)); + let span = stacktrace.first().map(|f| f.span).unwrap_or(ecx.tcx.span); + + let mut frames = Vec::new(); + + // Add notes to the backtrace. Don't print a single-line backtrace though. + if stacktrace.len() > 1 { + // Helper closure to print duplicated lines. + let mut add_frame = |mut frame: errors::FrameNote| { + frames.push(errors::FrameNote { times: 0, ..frame.clone() }); + // Don't print [... additional calls ...] if the number of lines is small + if frame.times < 3 { + let times = frame.times; + frame.times = 0; + frames.extend(std::iter::repeat(frame).take(times as usize)); + } else { + frames.push(frame); } - AssertFailure(msg) => write!(f, "{:?}", msg), - Panic { msg, line, col, file } => { - write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col) + }; + + let mut last_frame: Option = None; + for frame_info in &stacktrace { + let frame = frame_info.as_note(*ecx.tcx); + match last_frame.as_mut() { + Some(last_frame) + if last_frame.span == frame.span + && last_frame.where_ == frame.where_ + && last_frame.instance == frame.instance => + { + last_frame.times += 1; + } + Some(last_frame) => { + add_frame(mem::replace(last_frame, frame)); + } + None => { + last_frame = Some(frame); + } } - Abort(msg) => write!(f, "{}", msg), + } + if let Some(frame) = last_frame { + add_frame(frame); } } + + (span, frames) +} + +pub trait ReportErrorExt { + /// Returns the diagnostic message for this error. + fn diagnostic_message(&self) -> DiagnosticMessage; + fn add_args( + self, + handler: &Handler, + builder: &mut DiagnosticBuilder<'_, G>, + ); } -impl Error for ConstEvalErrKind {} +fn bad_pointer_message(msg: CheckInAllocMsg, handler: &Handler) -> String { + use crate::fluent_generated::*; -/// When const-evaluation errors, this type is constructed with the resulting information, -/// and then used to emit the error as a lint or hard error. -#[derive(Debug)] -pub(super) struct ConstEvalErr<'tcx> { - pub span: Span, - pub error: InterpError<'tcx>, - pub stacktrace: Vec>, + let msg = match msg { + CheckInAllocMsg::DerefTest => const_eval_deref_test, + CheckInAllocMsg::MemoryAccessTest => const_eval_memory_access_test, + CheckInAllocMsg::PointerArithmeticTest => const_eval_pointer_arithmetic_test, + CheckInAllocMsg::OffsetFromTest => const_eval_offset_from_test, + CheckInAllocMsg::InboundsTest => const_eval_in_bounds_test, + }; + + handler.eagerly_translate_to_string(msg, [].into_iter()) } -impl<'tcx> ConstEvalErr<'tcx> { - /// Turn an interpreter error into something to report to the user. - /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace. - /// Should be called only if the error is actually going to be reported! - pub fn new<'mir, M: Machine<'mir, 'tcx>>( - ecx: &InterpCx<'mir, 'tcx, M>, - error: InterpErrorInfo<'tcx>, - span: Option, - ) -> ConstEvalErr<'tcx> - where - 'tcx: 'mir, - { - error.print_backtrace(); - let mut stacktrace = ecx.generate_stacktrace(); - // Filter out `requires_caller_location` frames. - stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*ecx.tcx)); - // If `span` is missing, use topmost remaining frame, or else the "root" span from `ecx.tcx`. - let span = span.or_else(|| stacktrace.first().map(|f| f.span)).unwrap_or(ecx.tcx.span); - ConstEvalErr { error: error.into_kind(), stacktrace, span } - } - - pub(super) fn report(&self, tcx: TyCtxtAt<'tcx>, message: &str) -> ErrorHandled { - self.report_decorated(tcx, message, |_| {}) - } - - #[instrument(level = "trace", skip(self, decorate))] - pub(super) fn decorate(&self, err: &mut Diagnostic, decorate: impl FnOnce(&mut Diagnostic)) { - trace!("reporting const eval failure at {:?}", self.span); - // Add some more context for select error types. - match self.error { - InterpError::Unsupported( - UnsupportedOpInfo::ReadPointerAsBytes - | UnsupportedOpInfo::PartialPointerOverwrite(_) - | UnsupportedOpInfo::PartialPointerCopy(_), - ) => { - err.help("this code performed an operation that depends on the underlying bytes representing a pointer"); - err.help("the absolute address of a pointer is not known at compile-time, so such operations are not supported"); - } - _ => {} - } - // Add spans for the stacktrace. Don't print a single-line backtrace though. - if self.stacktrace.len() > 1 { - // Helper closure to print duplicated lines. - let mut flush_last_line = |last_frame: Option<(String, _)>, times| { - if let Some((line, span)) = last_frame { - err.span_note(span, line.clone()); - // Don't print [... additional calls ...] if the number of lines is small - if times < 3 { - for _ in 0..times { - err.span_note(span, line.clone()); - } - } else { - err.span_note( - span, - format!("[... {} additional calls {} ...]", times, &line), - ); - } +impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { + fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; + use UndefinedBehaviorInfo::*; + match self { + Ub(msg) => (&**msg).into(), + Unreachable => const_eval_unreachable, + BoundsCheckFailed { .. } => const_eval_bounds_check_failed, + DivisionByZero => const_eval_division_by_zero, + RemainderByZero => const_eval_remainder_by_zero, + DivisionOverflow => const_eval_division_overflow, + RemainderOverflow => const_eval_remainder_overflow, + PointerArithOverflow => const_eval_pointer_arithmetic_overflow, + InvalidMeta(InvalidMetaKind::SliceTooBig) => const_eval_invalid_meta_slice, + InvalidMeta(InvalidMetaKind::TooBig) => const_eval_invalid_meta, + UnterminatedCString(_) => const_eval_unterminated_c_string, + PointerUseAfterFree(_) => const_eval_pointer_use_after_free, + PointerOutOfBounds { ptr_size: Size::ZERO, .. } => const_eval_zst_pointer_out_of_bounds, + PointerOutOfBounds { .. } => const_eval_pointer_out_of_bounds, + DanglingIntPointer(0, _) => const_eval_dangling_null_pointer, + DanglingIntPointer(_, _) => const_eval_dangling_int_pointer, + AlignmentCheckFailed { .. } => const_eval_alignment_check_failed, + WriteToReadOnly(_) => const_eval_write_to_read_only, + DerefFunctionPointer(_) => const_eval_deref_function_pointer, + DerefVTablePointer(_) => const_eval_deref_vtable_pointer, + InvalidBool(_) => const_eval_invalid_bool, + InvalidChar(_) => const_eval_invalid_char, + InvalidTag(_) => const_eval_invalid_tag, + InvalidFunctionPointer(_) => const_eval_invalid_function_pointer, + InvalidVTablePointer(_) => const_eval_invalid_vtable_pointer, + InvalidStr(_) => const_eval_invalid_str, + InvalidUninitBytes(None) => const_eval_invalid_uninit_bytes_unknown, + InvalidUninitBytes(Some(_)) => const_eval_invalid_uninit_bytes, + DeadLocal => const_eval_dead_local, + ScalarSizeMismatch(_) => const_eval_scalar_size_mismatch, + UninhabitedEnumVariantWritten => const_eval_uninhabited_enum_variant_written, + Validation(e) => e.diagnostic_message(), + Custom(x) => (x.msg)(), + } + } + + fn add_args( + self, + handler: &Handler, + builder: &mut DiagnosticBuilder<'_, G>, + ) { + use UndefinedBehaviorInfo::*; + match self { + Ub(_) + | Unreachable + | DivisionByZero + | RemainderByZero + | DivisionOverflow + | RemainderOverflow + | PointerArithOverflow + | InvalidMeta(InvalidMetaKind::SliceTooBig) + | InvalidMeta(InvalidMetaKind::TooBig) + | InvalidUninitBytes(None) + | DeadLocal + | UninhabitedEnumVariantWritten => {} + BoundsCheckFailed { len, index } => { + builder.set_arg("len", len); + builder.set_arg("index", index); + } + UnterminatedCString(ptr) | InvalidFunctionPointer(ptr) | InvalidVTablePointer(ptr) => { + builder.set_arg("pointer", ptr); + } + PointerUseAfterFree(allocation) => { + builder.set_arg("allocation", allocation); + } + PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => { + builder + .set_arg("alloc_id", alloc_id) + .set_arg("alloc_size", alloc_size.bytes()) + .set_arg("ptr_offset", ptr_offset) + .set_arg("ptr_size", ptr_size.bytes()) + .set_arg("bad_pointer_message", bad_pointer_message(msg, handler)); + } + DanglingIntPointer(ptr, msg) => { + if ptr != 0 { + builder.set_arg("pointer", format!("{ptr:#x}[noalloc]")); } + + builder.set_arg("bad_pointer_message", bad_pointer_message(msg, handler)); + } + AlignmentCheckFailed { required, has } => { + builder.set_arg("required", required.bytes()); + builder.set_arg("has", has.bytes()); + } + WriteToReadOnly(alloc) | DerefFunctionPointer(alloc) | DerefVTablePointer(alloc) => { + builder.set_arg("allocation", alloc); + } + InvalidBool(b) => { + builder.set_arg("value", format!("{b:02x}")); + } + InvalidChar(c) => { + builder.set_arg("value", format!("{c:08x}")); + } + InvalidTag(tag) => { + builder.set_arg("tag", format!("{tag:x}")); + } + InvalidStr(err) => { + builder.set_arg("err", format!("{err}")); + } + InvalidUninitBytes(Some((alloc, info))) => { + builder.set_arg("alloc", alloc); + builder.set_arg("access", info.access); + builder.set_arg("uninit", info.uninit); + } + ScalarSizeMismatch(info) => { + builder.set_arg("target_size", info.target_size); + builder.set_arg("data_size", info.data_size); + } + Validation(e) => e.add_args(handler, builder), + Custom(custom) => { + (custom.add_args)(&mut |name, value| { + builder.set_arg(name, value); + }); + } + } + } +} + +impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> { + fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; + use ValidationErrorKind::*; + match self.kind { + PtrToUninhabited { ptr_kind: PointerKind::Box, .. } => const_eval_box_to_uninhabited, + PtrToUninhabited { ptr_kind: PointerKind::Ref, .. } => const_eval_ref_to_uninhabited, + + PtrToStatic { ptr_kind: PointerKind::Box } => const_eval_box_to_static, + PtrToStatic { ptr_kind: PointerKind::Ref } => const_eval_ref_to_static, + + PtrToMut { ptr_kind: PointerKind::Box } => const_eval_box_to_mut, + PtrToMut { ptr_kind: PointerKind::Ref } => const_eval_ref_to_mut, + + ExpectedNonPtr { .. } => const_eval_expected_non_ptr, + MutableRefInConst => const_eval_mutable_ref_in_const, + NullFnPtr => const_eval_null_fn_ptr, + NeverVal => const_eval_never_val, + NullablePtrOutOfRange { .. } => const_eval_nullable_ptr_out_of_range, + PtrOutOfRange { .. } => const_eval_ptr_out_of_range, + OutOfRange { .. } => const_eval_out_of_range, + UnsafeCell => const_eval_unsafe_cell, + UninhabitedVal { .. } => const_eval_uninhabited_val, + InvalidEnumTag { .. } => const_eval_invalid_enum_tag, + UninitEnumTag => const_eval_uninit_enum_tag, + UninitStr => const_eval_uninit_str, + Uninit { expected: ExpectedKind::Bool } => const_eval_uninit_bool, + Uninit { expected: ExpectedKind::Reference } => const_eval_uninit_ref, + Uninit { expected: ExpectedKind::Box } => const_eval_uninit_box, + Uninit { expected: ExpectedKind::RawPtr } => const_eval_uninit_raw_ptr, + Uninit { expected: ExpectedKind::InitScalar } => const_eval_uninit_init_scalar, + Uninit { expected: ExpectedKind::Char } => const_eval_uninit_char, + Uninit { expected: ExpectedKind::Float } => const_eval_uninit_float, + Uninit { expected: ExpectedKind::Int } => const_eval_uninit_int, + Uninit { expected: ExpectedKind::FnPtr } => const_eval_uninit_fn_ptr, + UninitVal => const_eval_uninit, + InvalidVTablePtr { .. } => const_eval_invalid_vtable_ptr, + InvalidMetaSliceTooLarge { ptr_kind: PointerKind::Box } => { + const_eval_invalid_box_slice_meta + } + InvalidMetaSliceTooLarge { ptr_kind: PointerKind::Ref } => { + const_eval_invalid_ref_slice_meta + } + + InvalidMetaTooLarge { ptr_kind: PointerKind::Box } => const_eval_invalid_box_meta, + InvalidMetaTooLarge { ptr_kind: PointerKind::Ref } => const_eval_invalid_ref_meta, + UnalignedPtr { ptr_kind: PointerKind::Ref, .. } => const_eval_unaligned_ref, + UnalignedPtr { ptr_kind: PointerKind::Box, .. } => const_eval_unaligned_box, + + NullPtr { ptr_kind: PointerKind::Box } => const_eval_null_box, + NullPtr { ptr_kind: PointerKind::Ref } => const_eval_null_ref, + DanglingPtrNoProvenance { ptr_kind: PointerKind::Box, .. } => { + const_eval_dangling_box_no_provenance + } + DanglingPtrNoProvenance { ptr_kind: PointerKind::Ref, .. } => { + const_eval_dangling_ref_no_provenance + } + DanglingPtrOutOfBounds { ptr_kind: PointerKind::Box } => { + const_eval_dangling_box_out_of_bounds + } + DanglingPtrOutOfBounds { ptr_kind: PointerKind::Ref } => { + const_eval_dangling_ref_out_of_bounds + } + DanglingPtrUseAfterFree { ptr_kind: PointerKind::Box } => { + const_eval_dangling_box_use_after_free + } + DanglingPtrUseAfterFree { ptr_kind: PointerKind::Ref } => { + const_eval_dangling_ref_use_after_free + } + InvalidBool { .. } => const_eval_validation_invalid_bool, + InvalidChar { .. } => const_eval_validation_invalid_char, + InvalidFnPtr { .. } => const_eval_invalid_fn_ptr, + } + } + + fn add_args(self, handler: &Handler, err: &mut DiagnosticBuilder<'_, G>) { + use crate::fluent_generated as fluent; + use ValidationErrorKind::*; + + let message = if let Some(path) = self.path { + handler.eagerly_translate_to_string( + fluent::const_eval_invalid_value_with_path, + [("path".into(), DiagnosticArgValue::Str(path.into()))].iter().map(|(a, b)| (a, b)), + ) + } else { + handler.eagerly_translate_to_string(fluent::const_eval_invalid_value, [].into_iter()) + }; + + err.set_arg("front_matter", message); + + fn add_range_arg( + r: WrappingRange, + max_hi: u128, + handler: &Handler, + err: &mut DiagnosticBuilder<'_, G>, + ) { + let WrappingRange { start: lo, end: hi } = r; + assert!(hi <= max_hi); + let msg = if lo > hi { + fluent::const_eval_range_wrapping + } else if lo == hi { + fluent::const_eval_range_singular + } else if lo == 0 { + assert!(hi < max_hi, "should not be printing if the range covers everything"); + fluent::const_eval_range_upper + } else if hi == max_hi { + assert!(lo > 0, "should not be printing if the range covers everything"); + fluent::const_eval_range_lower + } else { + fluent::const_eval_range }; - let mut last_frame = None; - let mut times = 0; - for frame_info in &self.stacktrace { - let frame = (frame_info.to_string(), frame_info.span); - if last_frame.as_ref() == Some(&frame) { - times += 1; - } else { - flush_last_line(last_frame, times); - last_frame = Some(frame); - times = 0; + let args = [ + ("lo".into(), DiagnosticArgValue::Str(lo.to_string().into())), + ("hi".into(), DiagnosticArgValue::Str(hi.to_string().into())), + ]; + let args = args.iter().map(|(a, b)| (a, b)); + let message = handler.eagerly_translate_to_string(msg, args); + err.set_arg("in_range", message); + } + + match self.kind { + PtrToUninhabited { ty, .. } | UninhabitedVal { ty } => { + err.set_arg("ty", ty); + } + ExpectedNonPtr { value } + | InvalidEnumTag { value } + | InvalidVTablePtr { value } + | InvalidBool { value } + | InvalidChar { value } + | InvalidFnPtr { value } => { + err.set_arg("value", value); + } + NullablePtrOutOfRange { range, max_value } | PtrOutOfRange { range, max_value } => { + add_range_arg(range, max_value, handler, err) + } + OutOfRange { range, max_value, value } => { + err.set_arg("value", value); + add_range_arg(range, max_value, handler, err); + } + UnalignedPtr { required_bytes, found_bytes, .. } => { + err.set_arg("required_bytes", required_bytes); + err.set_arg("found_bytes", found_bytes); + } + DanglingPtrNoProvenance { pointer, .. } => { + err.set_arg("pointer", pointer); + } + NullPtr { .. } + | PtrToStatic { .. } + | PtrToMut { .. } + | MutableRefInConst + | NullFnPtr + | NeverVal + | UnsafeCell + | UninitEnumTag + | UninitStr + | Uninit { .. } + | UninitVal + | InvalidMetaSliceTooLarge { .. } + | InvalidMetaTooLarge { .. } + | DanglingPtrUseAfterFree { .. } + | DanglingPtrOutOfBounds { .. } => {} + } + } +} + +impl ReportErrorExt for UnsupportedOpInfo { + fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; + match self { + UnsupportedOpInfo::Unsupported(s) => s.clone().into(), + UnsupportedOpInfo::PartialPointerOverwrite(_) => const_eval_partial_pointer_overwrite, + UnsupportedOpInfo::PartialPointerCopy(_) => const_eval_partial_pointer_copy, + UnsupportedOpInfo::ReadPointerAsBytes => const_eval_read_pointer_as_bytes, + UnsupportedOpInfo::ThreadLocalStatic(_) => const_eval_thread_local_static, + UnsupportedOpInfo::ReadExternStatic(_) => const_eval_read_extern_static, + } + } + fn add_args(self, _: &Handler, builder: &mut DiagnosticBuilder<'_, G>) { + use crate::fluent_generated::*; + + use UnsupportedOpInfo::*; + if let ReadPointerAsBytes | PartialPointerOverwrite(_) | PartialPointerCopy(_) = self { + builder.help(const_eval_ptr_as_bytes_1); + builder.help(const_eval_ptr_as_bytes_2); + } + match self { + Unsupported(_) | ReadPointerAsBytes => {} + PartialPointerOverwrite(ptr) | PartialPointerCopy(ptr) => { + builder.set_arg("ptr", ptr); + } + ThreadLocalStatic(did) | ReadExternStatic(did) => { + builder.set_arg("did", format!("{did:?}")); + } + } + } +} + +impl<'tcx> ReportErrorExt for InterpError<'tcx> { + fn diagnostic_message(&self) -> DiagnosticMessage { + match self { + InterpError::UndefinedBehavior(ub) => ub.diagnostic_message(), + InterpError::Unsupported(e) => e.diagnostic_message(), + InterpError::InvalidProgram(e) => e.diagnostic_message(), + InterpError::ResourceExhaustion(e) => e.diagnostic_message(), + InterpError::MachineStop(e) => e.diagnostic_message(), + } + } + fn add_args( + self, + handler: &Handler, + builder: &mut DiagnosticBuilder<'_, G>, + ) { + match self { + InterpError::UndefinedBehavior(ub) => ub.add_args(handler, builder), + InterpError::Unsupported(e) => e.add_args(handler, builder), + InterpError::InvalidProgram(e) => e.add_args(handler, builder), + InterpError::ResourceExhaustion(e) => e.add_args(handler, builder), + InterpError::MachineStop(e) => e.add_args(&mut |name, value| { + builder.set_arg(name, value); + }), + } + } +} + +impl<'tcx> ReportErrorExt for InvalidProgramInfo<'tcx> { + fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; + match self { + InvalidProgramInfo::TooGeneric => const_eval_too_generic, + InvalidProgramInfo::AlreadyReported(_) => const_eval_already_reported, + InvalidProgramInfo::Layout(e) => e.diagnostic_message(), + InvalidProgramInfo::FnAbiAdjustForForeignAbi(_) => { + rustc_middle::error::middle_adjust_for_foreign_abi_error + } + InvalidProgramInfo::SizeOfUnsizedType(_) => const_eval_size_of_unsized, + InvalidProgramInfo::UninitUnsizedLocal => const_eval_uninit_unsized_local, + } + } + fn add_args( + self, + handler: &Handler, + builder: &mut DiagnosticBuilder<'_, G>, + ) { + match self { + InvalidProgramInfo::TooGeneric + | InvalidProgramInfo::AlreadyReported(_) + | InvalidProgramInfo::UninitUnsizedLocal => {} + InvalidProgramInfo::Layout(e) => { + let diag: DiagnosticBuilder<'_, ()> = e.into_diagnostic().into_diagnostic(handler); + for (name, val) in diag.args() { + builder.set_arg(name.clone(), val.clone()); } + diag.cancel(); + } + InvalidProgramInfo::FnAbiAdjustForForeignAbi( + AdjustForForeignAbiError::Unsupported { arch, abi }, + ) => { + builder.set_arg("arch", arch); + builder.set_arg("abi", abi.name()); } - flush_last_line(last_frame, times); - } - // Let the caller attach any additional information it wants. - decorate(err); - } - - /// Create a diagnostic for this const eval error. - /// - /// Sets the message passed in via `message` and adds span labels with detailed error - /// information before handing control back to `decorate` to do any final annotations, - /// after which the diagnostic is emitted. - /// - /// If `lint_root.is_some()` report it as a lint, else report it as a hard error. - /// (Except that for some errors, we ignore all that -- see `must_error` below.) - #[instrument(skip(self, tcx, decorate), level = "debug")] - pub(super) fn report_decorated( - &self, - tcx: TyCtxtAt<'tcx>, - message: &str, - decorate: impl FnOnce(&mut Diagnostic), - ) -> ErrorHandled { - debug!("self.error: {:?}", self.error); - // Special handling for certain errors - match &self.error { - // Don't emit a new diagnostic for these errors - err_inval!(Layout(LayoutError::Unknown(_))) | err_inval!(TooGeneric) => { - ErrorHandled::TooGeneric - } - err_inval!(AlreadyReported(error_reported)) => ErrorHandled::Reported(*error_reported), - err_inval!(Layout(LayoutError::SizeOverflow(_))) => { - // We must *always* hard error on these, even if the caller wants just a lint. - // The `message` makes little sense here, this is a more serious error than the - // caller thinks anyway. - // See . - let mut err = struct_error(tcx, &self.error.to_string()); - self.decorate(&mut err, decorate); - ErrorHandled::Reported(err.emit().into()) - } - _ => { - // Report as hard error. - let mut err = struct_error(tcx, message); - err.span_label(self.span, self.error.to_string()); - self.decorate(&mut err, decorate); - ErrorHandled::Reported(err.emit().into()) + InvalidProgramInfo::SizeOfUnsizedType(ty) => { + builder.set_arg("ty", ty); } } } } + +impl ReportErrorExt for ResourceExhaustionInfo { + fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; + match self { + ResourceExhaustionInfo::StackFrameLimitReached => const_eval_stack_frame_limit_reached, + ResourceExhaustionInfo::StepLimitReached => const_eval_step_limit_reached, + ResourceExhaustionInfo::MemoryExhausted => const_eval_memory_exhausted, + ResourceExhaustionInfo::AddressSpaceFull => const_eval_address_space_full, + } + } + fn add_args(self, _: &Handler, _: &mut DiagnosticBuilder<'_, G>) {} +} + +/// Create a diagnostic for a const eval error. +/// +/// This will use the `mk` function for creating the error which will get passed labels according to +/// the `InterpError` and the span and a stacktrace of current execution according to +/// `get_span_and_frames`. +pub(super) fn report<'tcx, C, F, E>( + tcx: TyCtxt<'tcx>, + error: InterpError<'tcx>, + span: Option, + get_span_and_frames: C, + mk: F, +) -> ErrorHandled +where + C: FnOnce() -> (Span, Vec), + F: FnOnce(Span, Vec) -> E, + E: IntoDiagnostic<'tcx, ErrorGuaranteed>, +{ + // Special handling for certain errors + match error { + // Don't emit a new diagnostic for these errors + err_inval!(Layout(LayoutError::Unknown(_))) | err_inval!(TooGeneric) => { + ErrorHandled::TooGeneric + } + err_inval!(AlreadyReported(error_reported)) => ErrorHandled::Reported(error_reported), + err_inval!(Layout(layout_error @ LayoutError::SizeOverflow(_))) => { + // We must *always* hard error on these, even if the caller wants just a lint. + // The `message` makes little sense here, this is a more serious error than the + // caller thinks anyway. + // See . + let (our_span, frames) = get_span_and_frames(); + let span = span.unwrap_or(our_span); + let mut err = + tcx.sess.create_err(Spanned { span, node: layout_error.into_diagnostic() }); + err.code(rustc_errors::error_code!(E0080)); + let Some((mut err, handler)) = err.into_diagnostic() else { + panic!("did not emit diag"); + }; + for frame in frames { + err.eager_subdiagnostic(handler, frame); + } + + ErrorHandled::Reported(handler.emit_diagnostic(&mut err).unwrap().into()) + } + _ => { + // Report as hard error. + let (our_span, frames) = get_span_and_frames(); + let span = span.unwrap_or(our_span); + let err = mk(span, frames); + let mut err = tcx.sess.create_err(err); + + let msg = error.diagnostic_message(); + error.add_args(&tcx.sess.parse_sess.span_diagnostic, &mut err); + + // Use *our* span to label the interp error + err.span_label(our_span, msg); + ErrorHandled::Reported(err.emit().into()) + } + } +} diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 046d2052968a3..81808afcf7d06 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -1,12 +1,12 @@ use crate::const_eval::CheckAlignment; -use std::borrow::Cow; +use crate::errors::ConstEvalError; use either::{Left, Right}; use rustc_hir::def::DefKind; use rustc_middle::mir; -use rustc_middle::mir::interpret::ErrorHandled; -use rustc_middle::mir::pretty::display_allocation; +use rustc_middle::mir::interpret::{ErrorHandled, InterpErrorInfo}; +use rustc_middle::mir::pretty::write_allocation_bytes; use rustc_middle::traits::Reveal; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::print::with_no_trimmed_paths; @@ -14,7 +14,8 @@ use rustc_middle::ty::{self, TyCtxt}; use rustc_span::source_map::Span; use rustc_target::abi::{self, Abi}; -use super::{CompileTimeEvalContext, CompileTimeInterpreter, ConstEvalErr}; +use super::{CompileTimeEvalContext, CompileTimeInterpreter}; +use crate::errors; use crate::interpret::eval_nullary_intrinsic; use crate::interpret::{ intern_const_alloc_recursive, Allocation, ConstAlloc, ConstValue, CtfeValidationMode, GlobalId, @@ -22,10 +23,6 @@ use crate::interpret::{ RefTracking, StackPopCleanup, }; -const NOTE_ON_UNDEFINED_BEHAVIOR_ERROR: &str = "The rules on what exactly is undefined behavior aren't clear, \ - so this check might be overzealous. Please open an issue on the rustc \ - repository if you believe it should not be considered undefined behavior."; - // Returns a pointer to where the result lives fn eval_body_using_ecx<'mir, 'tcx>( ecx: &mut CompileTimeEvalContext<'mir, 'tcx>, @@ -253,8 +250,14 @@ pub fn eval_to_const_value_raw_provider<'tcx>( }; return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| { let span = tcx.def_span(def_id); - let error = ConstEvalErr { error: error.into_kind(), stacktrace: vec![], span }; - error.report(tcx.at(span), "could not evaluate nullary intrinsic") + + super::report( + tcx, + error.into_kind(), + Some(span), + || (span, vec![]), + |span, _| errors::NullaryIntrinsicError { span }, + ) }); } @@ -319,9 +322,11 @@ pub fn eval_to_allocation_raw_provider<'tcx>( let res = ecx.load_mir(cid.instance.def, cid.promoted); match res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body)) { Err(error) => { - let err = ConstEvalErr::new(&ecx, error, None); - let msg = if is_static { - Cow::from("could not evaluate static initializer") + let (error, backtrace) = error.into_parts(); + backtrace.print_backtrace(); + + let (kind, instance) = if is_static { + ("static", String::new()) } else { // If the current item has generics, we'd like to enrich the message with the // instance and its substs: to show the actual compile-time values, in addition to @@ -329,19 +334,29 @@ pub fn eval_to_allocation_raw_provider<'tcx>( let instance = &key.value.instance; if !instance.substs.is_empty() { let instance = with_no_trimmed_paths!(instance.to_string()); - let msg = format!("evaluation of `{}` failed", instance); - Cow::from(msg) + ("const_with_path", instance) } else { - Cow::from("evaluation of constant value failed") + ("const", String::new()) } }; - Err(err.report(ecx.tcx.at(err.span), &msg)) + Err(super::report( + *ecx.tcx, + error, + None, + || super::get_span_and_frames(&ecx), + |span, frames| ConstEvalError { + span, + error_kind: kind, + instance, + frame_notes: frames, + }, + )) } Ok(mplace) => { // Since evaluation had no errors, validate the resulting constant. // This is a separate `try` block to provide more targeted error reporting. - let validation = try { + let validation: Result<_, InterpErrorInfo<'_>> = try { let mut ref_tracking = RefTracking::new(mplace); let mut inner = false; while let Some((mplace, path)) = ref_tracking.todo.pop() { @@ -358,23 +373,37 @@ pub fn eval_to_allocation_raw_provider<'tcx>( } }; let alloc_id = mplace.ptr.provenance.unwrap(); + + // Validation failed, report an error. This is always a hard error. if let Err(error) = validation { - // Validation failed, report an error. This is always a hard error. - let err = ConstEvalErr::new(&ecx, error, None); - Err(err.report_decorated( - ecx.tcx, - "it is undefined behavior to use this value", - |diag| { - if matches!(err.error, InterpError::UndefinedBehavior(_)) { - diag.note(NOTE_ON_UNDEFINED_BEHAVIOR_ERROR); - } - diag.note(format!( - "the raw bytes of the constant ({}", - display_allocation( - *ecx.tcx, - ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner() - ) - )); + let (error, backtrace) = error.into_parts(); + backtrace.print_backtrace(); + + let ub_note = matches!(error, InterpError::UndefinedBehavior(_)).then(|| {}); + + let alloc = ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner(); + let mut bytes = String::new(); + if alloc.size() != abi::Size::ZERO { + bytes = "\n".into(); + // FIXME(translation) there might be pieces that are translatable. + write_allocation_bytes(*ecx.tcx, alloc, &mut bytes, " ").unwrap(); + } + let raw_bytes = errors::RawBytesNote { + size: alloc.size().bytes(), + align: alloc.align.bytes(), + bytes, + }; + + Err(super::report( + *ecx.tcx, + error, + None, + || super::get_span_and_frames(&ecx), + move |span, frames| errors::UndefinedBehavior { + span, + ub_note, + frames, + raw_bytes, }, )) } else { diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 58b5755af07f2..e44fbc420161e 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -25,6 +25,7 @@ use crate::interpret::{ self, compile_time_machine, AllocId, ConstAllocation, FnVal, Frame, ImmTy, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, Scalar, }; +use crate::{errors, fluent_generated as fluent}; use super::error::*; @@ -247,7 +248,10 @@ impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> { let target_align = self.read_scalar(&args[1])?.to_target_usize(self)?; if !target_align.is_power_of_two() { - throw_ub_format!("`align_offset` called with non-power-of-two align: {}", target_align); + throw_ub_custom!( + fluent::const_eval_align_offset_invalid_align, + target_align = target_align, + ); } match self.ptr_try_get_alloc_id(ptr) { @@ -353,15 +357,18 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, "`alignment_check_failed` called when no alignment check requested" ), CheckAlignment::FutureIncompat => { - let err = ConstEvalErr::new(ecx, err, None); - ecx.tcx.struct_span_lint_hir( + let (_, backtrace) = err.into_parts(); + backtrace.print_backtrace(); + let (span, frames) = super::get_span_and_frames(&ecx); + + ecx.tcx.emit_spanned_lint( INVALID_ALIGNMENT, ecx.stack().iter().find_map(|frame| frame.lint_root()).unwrap_or(CRATE_HIR_ID), - err.span, - err.error.to_string(), - |db| { - err.decorate(db, |_| {}); - db + span, + errors::AlignmentCheckFailed { + has: has.bytes(), + required: required.bytes(), + frames, }, ); Ok(()) @@ -475,7 +482,12 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, let align = match Align::from_bytes(align) { Ok(a) => a, - Err(err) => throw_ub_format!("align has to be a power of 2, {}", err), + Err(err) => throw_ub_custom!( + fluent::const_eval_invalid_align_details, + name = "const_allocate", + err_kind = err.diag_ident(), + align = err.align() + ), }; let ptr = ecx.allocate_ptr( @@ -493,7 +505,12 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, let size = Size::from_bytes(size); let align = match Align::from_bytes(align) { Ok(a) => a, - Err(err) => throw_ub_format!("align has to be a power of 2, {}", err), + Err(err) => throw_ub_custom!( + fluent::const_eval_invalid_align_details, + name = "const_deallocate", + err_kind = err.diag_ident(), + align = err.align() + ), }; // If an allocation is created in an another const, diff --git a/compiler/rustc_const_eval/src/const_eval/mod.rs b/compiler/rustc_const_eval/src/const_eval/mod.rs index 05be45fef1391..ed88d893e43a4 100644 --- a/compiler/rustc_const_eval/src/const_eval/mod.rs +++ b/compiler/rustc_const_eval/src/const_eval/mod.rs @@ -75,17 +75,8 @@ pub(crate) fn eval_to_valtree<'tcx>( let global_const_id = cid.display(tcx); match err { ValTreeCreationError::NodesOverflow => { - let msg = format!( - "maximum number of nodes exceeded in constant {}", - &global_const_id - ); - let mut diag = match tcx.hir().span_if_local(did) { - Some(span) => { - tcx.sess.create_err(MaxNumNodesInConstErr { span, global_const_id }) - } - None => tcx.sess.struct_err(msg), - }; - diag.emit(); + let span = tcx.hir().span_if_local(did); + tcx.sess.emit_err(MaxNumNodesInConstErr { span, global_const_id }); Ok(None) } diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index f8b7cc6d7e16b..fb20988008347 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -1,7 +1,15 @@ use rustc_hir::ConstContext; -use rustc_macros::Diagnostic; +use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; +use rustc_middle::ty::Ty; use rustc_span::Span; +#[derive(Diagnostic)] +#[diag(const_eval_dangling_ptr_in_final)] +pub(crate) struct DanglingPtrInFinal { + #[primary_span] + pub span: Span, +} + #[derive(Diagnostic)] #[diag(const_eval_unstable_in_stable)] pub(crate) struct UnstableInStable { @@ -92,7 +100,7 @@ pub(crate) struct TransientMutBorrowErrRaw { #[diag(const_eval_max_num_nodes_in_const)] pub(crate) struct MaxNumNodesInConstErr { #[primary_span] - pub span: Span, + pub span: Option, pub global_const_id: String, } @@ -175,6 +183,14 @@ pub(crate) struct UnallowedInlineAsm { pub kind: ConstContext, } +#[derive(Diagnostic)] +#[diag(const_eval_unsupported_untyped_pointer)] +#[note] +pub(crate) struct UnsupportedUntypedPointer { + #[primary_span] + pub span: Span, +} + #[derive(Diagnostic)] #[diag(const_eval_interior_mutable_data_refer, code = "E0492")] pub(crate) struct InteriorMutableDataRefer { @@ -194,3 +210,189 @@ pub(crate) struct InteriorMutabilityBorrow { #[primary_span] pub span: Span, } + +#[derive(Diagnostic)] +#[diag(const_eval_erroneous_constant)] +pub(crate) struct ErroneousConstUsed { + #[primary_span] + pub span: Span, +} + +#[derive(Subdiagnostic)] +#[note(const_eval_non_const_impl)] +pub(crate) struct NonConstImplNote { + #[primary_span] + pub span: Span, +} + +#[derive(Subdiagnostic, PartialEq, Eq, Clone)] +#[note(const_eval_frame_note)] +pub struct FrameNote { + #[primary_span] + pub span: Span, + pub times: i32, + pub where_: &'static str, + pub instance: String, +} + +#[derive(Subdiagnostic)] +#[note(const_eval_raw_bytes)] +pub struct RawBytesNote { + pub size: u64, + pub align: u64, + pub bytes: String, +} + +#[derive(Diagnostic)] +#[diag(const_eval_for_loop_into_iter_non_const, code = "E0015")] +pub struct NonConstForLoopIntoIter<'tcx> { + #[primary_span] + pub span: Span, + pub ty: Ty<'tcx>, + pub kind: ConstContext, +} + +#[derive(Diagnostic)] +#[diag(const_eval_question_branch_non_const, code = "E0015")] +pub struct NonConstQuestionBranch<'tcx> { + #[primary_span] + pub span: Span, + pub ty: Ty<'tcx>, + pub kind: ConstContext, +} + +#[derive(Diagnostic)] +#[diag(const_eval_question_from_residual_non_const, code = "E0015")] +pub struct NonConstQuestionFromResidual<'tcx> { + #[primary_span] + pub span: Span, + pub ty: Ty<'tcx>, + pub kind: ConstContext, +} + +#[derive(Diagnostic)] +#[diag(const_eval_try_block_from_output_non_const, code = "E0015")] +pub struct NonConstTryBlockFromOutput<'tcx> { + #[primary_span] + pub span: Span, + pub ty: Ty<'tcx>, + pub kind: ConstContext, +} + +#[derive(Diagnostic)] +#[diag(const_eval_await_non_const, code = "E0015")] +pub struct NonConstAwait<'tcx> { + #[primary_span] + pub span: Span, + pub ty: Ty<'tcx>, + pub kind: ConstContext, +} + +#[derive(Diagnostic)] +#[diag(const_eval_closure_non_const, code = "E0015")] +pub struct NonConstClosure { + #[primary_span] + pub span: Span, + pub kind: ConstContext, + #[subdiagnostic] + pub note: Option, +} + +#[derive(Subdiagnostic)] +pub enum NonConstClosureNote { + #[note(const_eval_closure_fndef_not_const)] + FnDef { + #[primary_span] + span: Span, + }, + #[note(const_eval_fn_ptr_call)] + FnPtr, + #[note(const_eval_closure_call)] + Closure, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion(const_eval_consider_dereferencing, applicability = "machine-applicable")] +pub struct ConsiderDereferencing { + pub deref: String, + #[suggestion_part(code = "{deref}")] + pub span: Span, + #[suggestion_part(code = "{deref}")] + pub rhs_span: Span, +} + +#[derive(Diagnostic)] +#[diag(const_eval_operator_non_const, code = "E0015")] +pub struct NonConstOperator { + #[primary_span] + pub span: Span, + pub kind: ConstContext, + #[subdiagnostic] + pub sugg: Option, +} + +#[derive(Diagnostic)] +#[diag(const_eval_deref_coercion_non_const, code = "E0015")] +#[note] +pub struct NonConstDerefCoercion<'tcx> { + #[primary_span] + pub span: Span, + pub ty: Ty<'tcx>, + pub kind: ConstContext, + pub target_ty: Ty<'tcx>, + #[note(const_eval_target_note)] + pub deref_target: Option, +} + +#[derive(Diagnostic)] +#[diag(const_eval_live_drop, code = "E0493")] +pub struct LiveDrop<'tcx> { + #[primary_span] + #[label] + pub span: Span, + pub kind: ConstContext, + pub dropped_ty: Ty<'tcx>, + #[label(const_eval_dropped_at_label)] + pub dropped_at: Option, +} + +#[derive(LintDiagnostic)] +#[diag(const_eval_align_check_failed)] +pub struct AlignmentCheckFailed { + pub has: u64, + pub required: u64, + #[subdiagnostic] + pub frames: Vec, +} + +#[derive(Diagnostic)] +#[diag(const_eval_error, code = "E0080")] +pub struct ConstEvalError { + #[primary_span] + pub span: Span, + /// One of "const", "const_with_path", and "static" + pub error_kind: &'static str, + pub instance: String, + #[subdiagnostic] + pub frame_notes: Vec, +} + +#[derive(Diagnostic)] +#[diag(const_eval_nullary_intrinsic_fail)] +pub struct NullaryIntrinsicError { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(const_eval_undefined_behavior, code = "E0080")] +pub struct UndefinedBehavior { + #[primary_span] + pub span: Span, + #[note(const_eval_undefined_behavior_note)] + pub ub_note: Option<()>, + #[subdiagnostic] + pub frames: Vec, + #[subdiagnostic] + pub raw_bytes: RawBytesNote, +} diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index 163e3f8699322..b4db3dff3ffc2 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -14,6 +14,8 @@ use super::{ util::ensure_monomorphic_enough, FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy, }; +use crate::fluent_generated as fluent; + impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { pub fn cast( &mut self, @@ -138,12 +140,16 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { assert!(src.layout.is_sized()); assert!(dest.layout.is_sized()); if src.layout.size != dest.layout.size { - throw_ub_format!( - "transmuting from {}-byte type to {}-byte type: `{}` -> `{}`", - src.layout.size.bytes(), - dest.layout.size.bytes(), - src.layout.ty, - dest.layout.ty, + let src_bytes = src.layout.size.bytes(); + let dest_bytes = dest.layout.size.bytes(); + let src_ty = format!("{}", src.layout.ty); + let dest_ty = format!("{}", dest.layout.ty); + throw_ub_custom!( + fluent::const_eval_invalid_transmute, + src_bytes = src_bytes, + dest_bytes = dest_bytes, + src = src_ty, + dest = dest_ty, ); } @@ -363,7 +369,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let old_vptr = old_vptr.to_pointer(self)?; let (ty, old_trait) = self.get_ptr_vtable(old_vptr)?; if old_trait != data_a.principal() { - throw_ub_format!("upcast on a pointer whose vtable does not match its type"); + throw_ub_custom!(fluent::const_eval_upcast_mismatch); } let new_vptr = self.get_vtable_ptr(ty, data_b.principal())?; self.write_immediate(Immediate::new_dyn_trait(old_data, new_vptr, self), dest) diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 040eba10eb4f7..e37609beea9bc 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -1,13 +1,12 @@ use std::cell::Cell; -use std::fmt; -use std::mem; +use std::{fmt, mem}; use either::{Either, Left, Right}; use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData}; use rustc_index::IndexVec; use rustc_middle::mir; -use rustc_middle::mir::interpret::{ErrorHandled, InterpError, ReportedErrorInfo}; +use rustc_middle::mir::interpret::{ErrorHandled, InterpError, InvalidMetaKind, ReportedErrorInfo}; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::{ self, FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOf, LayoutOfHelpers, @@ -24,6 +23,8 @@ use super::{ MemPlaceMeta, Memory, MemoryKind, Operand, Place, PlaceTy, PointerArithmetic, Provenance, Scalar, StackPopJump, }; +use crate::errors::{self, ErroneousConstUsed}; +use crate::fluent_generated as fluent; use crate::util; pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> { @@ -246,6 +247,7 @@ impl<'mir, 'tcx, Prov: Provenance, Extra> Frame<'mir, 'tcx, Prov, Extra> { } } +// FIXME: only used by miri, should be removed once translatable. impl<'tcx> fmt::Display for FrameInfo<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { @@ -263,6 +265,21 @@ impl<'tcx> fmt::Display for FrameInfo<'tcx> { } } +impl<'tcx> FrameInfo<'tcx> { + pub fn as_note(&self, tcx: TyCtxt<'tcx>) -> errors::FrameNote { + let span = self.span; + if tcx.def_key(self.instance.def_id()).disambiguated_data.data == DefPathData::ClosureExpr { + errors::FrameNote { where_: "closure", span, instance: String::new(), times: 0 } + } else { + let instance = format!("{}", self.instance); + // Note: this triggers a `good_path_bug` state, which means that if we ever get here + // we must emit a diagnostic. We should never display a `FrameInfo` unless we + // actually want to emit a warning or error to the user. + errors::FrameNote { where_: "instance", span, instance, times: 0 } + } + } +} + impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> { #[inline] fn data_layout(&self) -> &TargetDataLayout { @@ -610,7 +627,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Check if this brought us over the size limit. if size > self.max_size_of_val() { - throw_ub!(InvalidMeta("total size is bigger than largest supported object")); + throw_ub!(InvalidMeta(InvalidMetaKind::TooBig)); } Ok(Some((size, align))) } @@ -628,7 +645,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let size = elem.size.bytes().saturating_mul(len); // we rely on `max_size_of_val` being smaller than `u64::MAX`. let size = Size::from_bytes(size); if size > self.max_size_of_val() { - throw_ub!(InvalidMeta("slice is bigger than largest supported object")); + throw_ub!(InvalidMeta(InvalidMetaKind::SliceTooBig)); } Ok(Some((size, elem.align.abi))) } @@ -736,7 +753,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { mir::UnwindAction::Cleanup(block) => Left(mir::Location { block, statement_index: 0 }), mir::UnwindAction::Continue => Right(self.frame_mut().body.span), mir::UnwindAction::Unreachable => { - throw_ub_format!("unwinding past a stack frame that does not allow unwinding") + throw_ub_custom!(fluent::const_eval_unreachable_unwind); } mir::UnwindAction::Terminate => { self.frame_mut().loc = Right(self.frame_mut().body.span); @@ -775,7 +792,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } ); if unwinding && self.frame_idx() == 0 { - throw_ub_format!("unwinding past the topmost frame of the stack"); + throw_ub_custom!(fluent::const_eval_unwind_past_top); } // Copy return value. Must of course happen *before* we deallocate the locals. @@ -863,7 +880,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // StorageLive expects the local to be dead, and marks it live. let old = mem::replace(&mut self.frame_mut().locals[local].value, local_val); if !matches!(old, LocalValue::Dead) { - throw_ub_format!("StorageLive on a local that was already live"); + throw_ub_custom!(fluent::const_eval_double_storage_live); } Ok(()) } @@ -906,7 +923,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ErrorHandled::Reported(err) => { if !err.is_tainted_by_errors() && let Some(span) = span { // To make it easier to figure out where this error comes from, also add a note at the current location. - self.tcx.sess.span_note_without_error(span, "erroneous constant used"); + self.tcx.sess.emit_note(ErroneousConstUsed { span }); } err_inval!(AlreadyReported(err)) } diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index c2b82ba9b0792..7b11ad33091e4 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -28,6 +28,7 @@ use super::{ ValueVisitor, }; use crate::const_eval; +use crate::errors::{DanglingPtrInFinal, UnsupportedUntypedPointer}; pub trait CompileTimeMachine<'mir, 'tcx, T> = Machine< 'mir, @@ -320,10 +321,12 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx, const_eval::Memory } } +/// How a constant value should be interned. #[derive(Copy, Clone, Debug, PartialEq, Hash, Eq)] pub enum InternKind { /// The `mutability` of the static, ignoring the type which may have interior mutability. Static(hir::Mutability), + /// A `const` item Constant, Promoted, } @@ -388,8 +391,7 @@ pub fn intern_const_alloc_recursive< ecx.tcx.sess.delay_span_bug( ecx.tcx.span, format!( - "error during interning should later cause validation failure: {}", - error + "error during interning should later cause validation failure: {error:?}" ), ); } @@ -425,14 +427,16 @@ pub fn intern_const_alloc_recursive< // immutability is so important. alloc.mutability = Mutability::Not; } + // If it's a constant, we should not have any "leftovers" as everything + // is tracked by const-checking. + // FIXME: downgrade this to a warning? It rejects some legitimate consts, + // such as `const CONST_RAW: *const Vec = &Vec::new() as *const _;`. + // + // NOTE: it looks likes this code path is only reachable when we try to intern + // something that cannot be promoted, which in constants means values that have + // drop glue, such as the example above. InternKind::Constant => { - // If it's a constant, we should not have any "leftovers" as everything - // is tracked by const-checking. - // FIXME: downgrade this to a warning? It rejects some legitimate consts, - // such as `const CONST_RAW: *const Vec = &Vec::new() as *const _;`. - ecx.tcx - .sess - .span_err(ecx.tcx.span, "untyped pointers are not allowed in constant"); + ecx.tcx.sess.emit_err(UnsupportedUntypedPointer { span: ecx.tcx.span }); // For better errors later, mark the allocation as immutable. alloc.mutability = Mutability::Not; } @@ -447,10 +451,7 @@ pub fn intern_const_alloc_recursive< } else if ecx.memory.dead_alloc_map.contains_key(&alloc_id) { // Codegen does not like dangling pointers, and generally `tcx` assumes that // all allocations referenced anywhere actually exist. So, make sure we error here. - let reported = ecx - .tcx - .sess - .span_err(ecx.tcx.span, "encountered dangling pointer in final constant"); + let reported = ecx.tcx.sess.emit_err(DanglingPtrInFinal { span: ecx.tcx.span }); return Err(reported); } else if ecx.tcx.try_get_global_alloc(alloc_id).is_none() { // We have hit an `AllocId` that is neither in local or global memory and isn't diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index a77c699c22f7e..fb24cf48a9a02 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -22,6 +22,8 @@ use super::{ Pointer, }; +use crate::fluent_generated as fluent; + mod caller_location; fn numeric_intrinsic(name: Symbol, bits: u128, kind: Primitive) -> Scalar { @@ -198,15 +200,18 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ty ), }; - let (nonzero, intrinsic_name) = match intrinsic_name { + let (nonzero, actual_intrinsic_name) = match intrinsic_name { sym::cttz_nonzero => (true, sym::cttz), sym::ctlz_nonzero => (true, sym::ctlz), other => (false, other), }; if nonzero && bits == 0 { - throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name); + throw_ub_custom!( + fluent::const_eval_call_nonzero_intrinsic, + name = intrinsic_name, + ); } - let out_val = numeric_intrinsic(intrinsic_name, bits, kind); + let out_val = numeric_intrinsic(actual_intrinsic_name, bits, kind); self.write_scalar(out_val, dest)?; } sym::saturating_add | sym::saturating_sub => { @@ -253,9 +258,13 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let layout = self.layout_of(substs.type_at(0))?; let r_val = r.to_scalar().to_bits(layout.size)?; if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name { - throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name); + throw_ub_custom!( + fluent::const_eval_overflow_shift, + val = r_val, + name = intrinsic_name + ); } else { - throw_ub_format!("overflow executing `{}`", intrinsic_name); + throw_ub_custom!(fluent::const_eval_overflow, name = intrinsic_name); } } self.write_scalar(val, dest)?; @@ -314,17 +323,17 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { (Err(_), _) | (_, Err(_)) => { // We managed to find a valid allocation for one pointer, but not the other. // That means they are definitely not pointing to the same allocation. - throw_ub_format!( - "`{}` called on pointers into different allocations", - intrinsic_name + throw_ub_custom!( + fluent::const_eval_different_allocations, + name = intrinsic_name, ); } (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) => { // Found allocation for both. They must be into the same allocation. if a_alloc_id != b_alloc_id { - throw_ub_format!( - "`{}` called on pointers into different allocations", - intrinsic_name + throw_ub_custom!( + fluent::const_eval_different_allocations, + name = intrinsic_name, ); } // Use these offsets for distance calculation. @@ -344,11 +353,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { if overflowed { // a < b if intrinsic_name == sym::ptr_offset_from_unsigned { - throw_ub_format!( - "`{}` called when first pointer has smaller offset than second: {} < {}", - intrinsic_name, - a_offset, - b_offset, + throw_ub_custom!( + fluent::const_eval_unsigned_offset_from_overflow, + a_offset = a_offset, + b_offset = b_offset, ); } // The signed form of the intrinsic allows this. If we interpret the @@ -356,9 +364,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // seems *positive*, they were more than isize::MAX apart. let dist = val.to_target_isize(self)?; if dist >= 0 { - throw_ub_format!( - "`{}` called when first pointer is too far before second", - intrinsic_name + throw_ub_custom!( + fluent::const_eval_offset_from_underflow, + name = intrinsic_name, ); } dist @@ -368,9 +376,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // If converting to isize produced a *negative* result, we had an overflow // because they were more than isize::MAX apart. if dist < 0 { - throw_ub_format!( - "`{}` called when first pointer is too far ahead of second", - intrinsic_name + throw_ub_custom!( + fluent::const_eval_offset_from_overflow, + name = intrinsic_name, ); } dist @@ -513,7 +521,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let op = self.eval_operand(op, None)?; let cond = self.read_scalar(&op)?.to_bool()?; if !cond { - throw_ub_format!("`assume` called with `false`"); + throw_ub_custom!(fluent::const_eval_assume_false); } Ok(()) } @@ -542,7 +550,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?; assert!(!overflow); // All overflow is UB, so this should never return on overflow. if res.assert_bits(a.layout.size) != 0 { - throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b) + throw_ub_custom!( + fluent::const_eval_exact_div_has_remainder, + a = format!("{a}"), + b = format!("{b}") + ) } // `Rem` says this is all right, so we can let `Div` do its job. self.binop_ignore_overflow(BinOp::Div, &a, &b, dest) @@ -638,9 +650,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max), // but no actual allocation can be big enough for the difference to be noticeable. let size = size.checked_mul(count, self).ok_or_else(|| { - err_ub_format!( - "overflow computing total size of `{}`", - if nonoverlapping { "copy_nonoverlapping" } else { "copy" } + err_ub_custom!( + fluent::const_eval_size_overflow, + name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" } ) })?; @@ -664,10 +676,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max), // but no actual allocation can be big enough for the difference to be noticeable. - let len = layout - .size - .checked_mul(count, self) - .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?; + let len = layout.size.checked_mul(count, self).ok_or_else(|| { + err_ub_custom!(fluent::const_eval_size_overflow, name = "write_bytes") + })?; let bytes = std::iter::repeat(byte).take(len.bytes_usize()); self.write_bytes_ptr(dst, bytes) @@ -691,7 +702,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { return Ok(&[]); }; if alloc_ref.has_provenance() { - throw_ub_format!("`raw_eq` on bytes with provenance"); + throw_ub_custom!(fluent::const_eval_raw_eq_with_provenance); } alloc_ref.get_bytes_strip_provenance() }; diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index d5b6a581a79f6..1125d8d1f0e08 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -19,6 +19,7 @@ use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TyCtxt}; use rustc_target::abi::{Align, HasDataLayout, Size}; use crate::const_eval::CheckAlignment; +use crate::fluent_generated as fluent; use super::{ alloc_range, AllocBytes, AllocId, AllocMap, AllocRange, Allocation, CheckInAllocMsg, @@ -200,7 +201,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { align: Align, kind: MemoryKind, ) -> InterpResult<'tcx, Pointer> { - let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?; + let alloc = if M::PANIC_ON_ALLOC_FAIL { + Allocation::uninit(size, align) + } else { + Allocation::try_uninit(size, align)? + }; self.allocate_raw_ptr(alloc, kind) } @@ -242,9 +247,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ) -> InterpResult<'tcx, Pointer> { let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr)?; if offset.bytes() != 0 { - throw_ub_format!( - "reallocating {:?} which does not point to the beginning of an object", - ptr + throw_ub_custom!( + fluent::const_eval_realloc_or_alloc_with_offset, + ptr = format!("{ptr:?}"), + kind = "realloc" ); } @@ -280,9 +286,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("deallocating: {alloc_id:?}"); if offset.bytes() != 0 { - throw_ub_format!( - "deallocating {:?} which does not point to the beginning of an object", - ptr + throw_ub_custom!( + fluent::const_eval_realloc_or_alloc_with_offset, + ptr = format!("{ptr:?}"), + kind = "dealloc", ); } @@ -290,13 +297,25 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Deallocating global memory -- always an error return Err(match self.tcx.try_get_global_alloc(alloc_id) { Some(GlobalAlloc::Function(..)) => { - err_ub_format!("deallocating {alloc_id:?}, which is a function") + err_ub_custom!( + fluent::const_eval_invalid_dealloc, + alloc_id = alloc_id, + kind = "fn", + ) } Some(GlobalAlloc::VTable(..)) => { - err_ub_format!("deallocating {alloc_id:?}, which is a vtable") + err_ub_custom!( + fluent::const_eval_invalid_dealloc, + alloc_id = alloc_id, + kind = "vtable", + ) } Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => { - err_ub_format!("deallocating {alloc_id:?}, which is static memory") + err_ub_custom!( + fluent::const_eval_invalid_dealloc, + alloc_id = alloc_id, + kind = "static_mem" + ) } None => err_ub!(PointerUseAfterFree(alloc_id)), } @@ -304,21 +323,25 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { }; if alloc.mutability.is_not() { - throw_ub_format!("deallocating immutable allocation {alloc_id:?}"); + throw_ub_custom!(fluent::const_eval_dealloc_immutable, alloc = alloc_id,); } if alloc_kind != kind { - throw_ub_format!( - "deallocating {alloc_id:?}, which is {alloc_kind} memory, using {kind} deallocation operation" + throw_ub_custom!( + fluent::const_eval_dealloc_kind_mismatch, + alloc = alloc_id, + alloc_kind = format!("{alloc_kind}"), + kind = format!("{kind}"), ); } if let Some((size, align)) = old_size_and_align { if size != alloc.size() || align != alloc.align { - throw_ub_format!( - "incorrect layout on deallocation: {alloc_id:?} has size {} and alignment {}, but gave size {} and alignment {}", - alloc.size().bytes(), - alloc.align.bytes(), - size.bytes(), - align.bytes(), + throw_ub_custom!( + fluent::const_eval_dealloc_incorrect_layout, + alloc = alloc_id, + size = alloc.size().bytes(), + align = alloc.align.bytes(), + size_found = size.bytes(), + align_found = align.bytes(), ) } } @@ -1166,7 +1189,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { if (src_offset <= dest_offset && src_offset + size > dest_offset) || (dest_offset <= src_offset && dest_offset + size > src_offset) { - throw_ub_format!("copy_nonoverlapping called on overlapping ranges") + throw_ub_custom!(fluent::const_eval_copy_nonoverlapping_overlapping); } } diff --git a/compiler/rustc_const_eval/src/interpret/terminator.rs b/compiler/rustc_const_eval/src/interpret/terminator.rs index df3879200101b..b8697527ec916 100644 --- a/compiler/rustc_const_eval/src/interpret/terminator.rs +++ b/compiler/rustc_const_eval/src/interpret/terminator.rs @@ -15,6 +15,7 @@ use super::{ FnVal, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemoryKind, OpTy, Operand, PlaceTy, Scalar, StackPopCleanup, }; +use crate::fluent_generated as fluent; impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { pub(super) fn eval_terminator( @@ -172,7 +173,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { InlineAsm { template, ref operands, options, destination, .. } => { M::eval_inline_asm(self, template, operands, options)?; if options.contains(InlineAsmOptions::NORETURN) { - throw_ub_format!("returned from noreturn inline assembly"); + throw_ub_custom!(fluent::const_eval_noreturn_asm_returned); } self.go_to_block( destination @@ -288,15 +289,17 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { return Ok(()); } // Find next caller arg. - let (caller_arg, caller_abi) = caller_args.next().ok_or_else(|| { - err_ub_format!("calling a function with fewer arguments than it requires") - })?; + let Some((caller_arg, caller_abi)) = caller_args.next() else { + throw_ub_custom!(fluent::const_eval_not_enough_caller_args); + }; // Now, check if !Self::check_argument_compat(caller_abi, callee_abi) { - throw_ub_format!( - "calling a function with argument of type {:?} passing data of type {:?}", - callee_arg.layout.ty, - caller_arg.layout.ty + let callee_ty = format!("{}", callee_arg.layout.ty); + let caller_ty = format!("{}", caller_arg.layout.ty); + throw_ub_custom!( + fluent::const_eval_incompatible_types, + callee_ty = callee_ty, + caller_ty = caller_ty, ) } // Special handling for unsized parameters. @@ -398,10 +401,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { if M::enforce_abi(self) { if caller_fn_abi.conv != callee_fn_abi.conv { - throw_ub_format!( - "calling a function with calling convention {:?} using calling convention {:?}", - callee_fn_abi.conv, - caller_fn_abi.conv + throw_ub_custom!( + fluent::const_eval_incompatible_calling_conventions, + callee_conv = format!("{:?}", callee_fn_abi.conv), + caller_conv = format!("{:?}", caller_fn_abi.conv), ) } } @@ -508,15 +511,16 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { "mismatch between callee ABI and callee body arguments" ); if caller_args.next().is_some() { - throw_ub_format!("calling a function with more arguments than it expected") + throw_ub_custom!(fluent::const_eval_too_many_caller_args); } // Don't forget to check the return type! if !Self::check_argument_compat(&caller_fn_abi.ret, &callee_fn_abi.ret) { - throw_ub_format!( - "calling a function with return type {:?} passing \ - return place of type {:?}", - callee_fn_abi.ret.layout.ty, - caller_fn_abi.ret.layout.ty, + let callee_ty = format!("{}", callee_fn_abi.ret.layout.ty); + let caller_ty = format!("{}", caller_fn_abi.ret.layout.ty); + throw_ub_custom!( + fluent::const_eval_incompatible_return_types, + callee_ty = callee_ty, + caller_ty = caller_ty, ) } }; @@ -587,9 +591,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let (recv, vptr) = self.unpack_dyn_star(&receiver_place.into())?; let (dyn_ty, dyn_trait) = self.get_ptr_vtable(vptr)?; if dyn_trait != data.principal() { - throw_ub_format!( - "`dyn*` call on a pointer whose vtable does not match its type" - ); + throw_ub_custom!(fluent::const_eval_dyn_star_call_vtable_mismatch); } let recv = recv.assert_mem_place(); // we passed an MPlaceTy to `unpack_dyn_star` so we definitely still have one @@ -609,9 +611,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let vptr = receiver_place.meta.unwrap_meta().to_pointer(self)?; let (dyn_ty, dyn_trait) = self.get_ptr_vtable(vptr)?; if dyn_trait != data.principal() { - throw_ub_format!( - "`dyn` call on a pointer whose vtable does not match its type" - ); + throw_ub_custom!(fluent::const_eval_dyn_call_vtable_mismatch); } // It might be surprising that we use a pointer as the receiver even if this @@ -623,7 +623,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Now determine the actual method to call. We can do that in two different ways and // compare them to ensure everything fits. let Some(ty::VtblEntry::Method(fn_inst)) = self.get_vtable_entries(vptr)?.get(idx).copied() else { - throw_ub_format!("`dyn` call trying to call something that is not a method") + // FIXME(fee1-dead) these could be variants of the UB info enum instead of this + throw_ub_custom!(fluent::const_eval_dyn_call_not_a_method); }; trace!("Virtual call dispatches to {fn_inst:#?}"); if cfg!(debug_assertions) { diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 01b77289937fb..21c655988a0e1 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -4,7 +4,7 @@ //! That's useful because it means other passes (e.g. promotion) can rely on `const`s //! to be const-safe. -use std::fmt::{Display, Write}; +use std::fmt::Write; use std::num::NonZeroUsize; use either::{Left, Right}; @@ -12,7 +12,10 @@ use either::{Left, Right}; use rustc_ast::Mutability; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; -use rustc_middle::mir::interpret::InterpError; +use rustc_middle::mir::interpret::{ + ExpectedKind, InterpError, InvalidMetaKind, PointerKind, ValidationErrorInfo, + ValidationErrorKind, ValidationErrorKind::*, +}; use rustc_middle::ty; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_span::symbol::{sym, Symbol}; @@ -30,14 +33,7 @@ use super::{ }; macro_rules! throw_validation_failure { - ($where:expr, { $( $what_fmt:tt )* } $( expected { $( $expected_fmt:tt )* } )?) => {{ - let mut msg = String::new(); - msg.push_str("encountered "); - write!(&mut msg, $($what_fmt)*).unwrap(); - $( - msg.push_str(", but expected "); - write!(&mut msg, $($expected_fmt)*).unwrap(); - )? + ($where:expr, $kind: expr) => {{ let where_ = &$where; let path = if !where_.is_empty() { let mut path = String::new(); @@ -46,7 +42,8 @@ macro_rules! throw_validation_failure { } else { None }; - throw_ub!(ValidationFailure { path, msg }) + + throw_ub!(Validation(ValidationErrorInfo { path, kind: $kind })) }}; } @@ -82,22 +79,22 @@ macro_rules! throw_validation_failure { /// macro_rules! try_validation { ($e:expr, $where:expr, - $( $( $p:pat_param )|+ => { $( $what_fmt:tt )* } $( expected { $( $expected_fmt:tt )* } )? ),+ $(,)? + $( $( $p:pat_param )|+ => $kind: expr ),+ $(,)? ) => {{ match $e { Ok(x) => x, // We catch the error and turn it into a validation failure. We are okay with // allocation here as this can only slow down builds that fail anyway. - Err(e) => match e.kind() { + Err(e) => match e.into_parts() { $( - InterpError::UndefinedBehavior($($p)|+) => + (InterpError::UndefinedBehavior($($p)|+), _) => throw_validation_failure!( $where, - { $( $what_fmt )* } $( expected { $( $expected_fmt )* } )? + $kind ) ),+, #[allow(unreachable_patterns)] - _ => Err::(e)?, + (e, rest) => Err::($crate::interpret::InterpErrorInfo::from_parts(e, rest))?, } } }}; @@ -160,6 +157,7 @@ impl RefTracking } } +// FIXME make this translatable as well? /// Format a path fn write_path(out: &mut String, path: &[PathElem]) { use self::PathElem::*; @@ -185,26 +183,6 @@ fn write_path(out: &mut String, path: &[PathElem]) { } } -// Formats such that a sentence like "expected something {}" to mean -// "expected something " makes sense. -fn wrapping_range_format(r: WrappingRange, max_hi: u128) -> String { - let WrappingRange { start: lo, end: hi } = r; - assert!(hi <= max_hi); - if lo > hi { - format!("less or equal to {}, or greater or equal to {}", hi, lo) - } else if lo == hi { - format!("equal to {}", lo) - } else if lo == 0 { - assert!(hi < max_hi, "should not be printing if the range covers everything"); - format!("less or equal to {}", hi) - } else if hi == max_hi { - assert!(lo > 0, "should not be printing if the range covers everything"); - format!("greater or equal to {}", lo) - } else { - format!("in the range {:?}", r) - } -} - struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> { /// The `path` may be pushed to, but the part that is present when a function /// starts must not be changed! `visit_fields` and `visit_array` rely on @@ -311,19 +289,19 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' fn read_immediate( &self, op: &OpTy<'tcx, M::Provenance>, - expected: impl Display, + expected: ExpectedKind, ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> { Ok(try_validation!( self.ecx.read_immediate(op), self.path, - InvalidUninitBytes(None) => { "uninitialized memory" } expected { "{expected}" } + InvalidUninitBytes(None) => Uninit { expected } )) } fn read_scalar( &self, op: &OpTy<'tcx, M::Provenance>, - expected: impl Display, + expected: ExpectedKind, ) -> InterpResult<'tcx, Scalar> { Ok(self.read_immediate(op, expected)?.to_scalar()) } @@ -342,8 +320,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' self.ecx.get_ptr_vtable(vtable), self.path, DanglingIntPointer(..) | - InvalidVTablePointer(..) => - { "{vtable}" } expected { "a vtable pointer" }, + InvalidVTablePointer(..) => InvalidVTablePtr { value: format!("{vtable}") } ); // FIXME: check if the type/trait match what ty::Dynamic says? } @@ -366,10 +343,9 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' fn check_safe_pointer( &mut self, value: &OpTy<'tcx, M::Provenance>, - kind: &str, + ptr_kind: PointerKind, ) -> InterpResult<'tcx> { - let place = - self.ecx.ref_to_mplace(&self.read_immediate(value, format_args!("a {kind}"))?)?; + let place = self.ecx.ref_to_mplace(&self.read_immediate(value, ptr_kind.into())?)?; // Handle wide pointers. // Check metadata early, for better diagnostics if place.layout.is_unsized() { @@ -379,7 +355,10 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' let size_and_align = try_validation!( self.ecx.size_and_align_of_mplace(&place), self.path, - InvalidMeta(msg) => { "invalid {} metadata: {}", kind, msg }, + InvalidMeta(msg) => match msg { + InvalidMetaKind::SliceTooBig => InvalidMetaSliceTooLarge { ptr_kind }, + InvalidMetaKind::TooBig => InvalidMetaTooLarge { ptr_kind }, + } ); let (size, align) = size_and_align // for the purpose of validity, consider foreign types to have @@ -395,31 +374,30 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message ), self.path, - AlignmentCheckFailed { required, has } => - { - "an unaligned {kind} (required {} byte alignment but found {})", - required.bytes(), - has.bytes(), - }, - DanglingIntPointer(0, _) => - { "a null {kind}" }, - DanglingIntPointer(i, _) => - { - "a dangling {kind} ({pointer} has no provenance)", - pointer = Pointer::>::from_addr_invalid(*i), - }, - PointerOutOfBounds { .. } => - { "a dangling {kind} (going beyond the bounds of its allocation)" }, + AlignmentCheckFailed { required, has } => UnalignedPtr { + ptr_kind, + required_bytes: required.bytes(), + found_bytes: has.bytes() + }, + DanglingIntPointer(0, _) => NullPtr { ptr_kind }, + DanglingIntPointer(i, _) => DanglingPtrNoProvenance { + ptr_kind, + // FIXME this says "null pointer" when null but we need translate + pointer: format!("{}", Pointer::>::from_addr_invalid(i)) + }, + PointerOutOfBounds { .. } => DanglingPtrOutOfBounds { + ptr_kind + }, // This cannot happen during const-eval (because interning already detects // dangling pointers), but it can happen in Miri. - PointerUseAfterFree(..) => - { "a dangling {kind} (use-after-free)" }, + PointerUseAfterFree(..) => DanglingPtrUseAfterFree { + ptr_kind, + }, ); // Do not allow pointers to uninhabited types. if place.layout.abi.is_uninhabited() { - throw_validation_failure!(self.path, - { "a {kind} pointing to uninhabited type {}", place.layout.ty } - ) + let ty = place.layout.ty; + throw_validation_failure!(self.path, PtrToUninhabited { ptr_kind, ty }) } // Recursive checking if let Some(ref_tracking) = self.ref_tracking.as_deref_mut() { @@ -441,9 +419,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' // this check is so important. // This check is reachable when the const just referenced the static, // but never read it (so we never entered `before_access_global`). - throw_validation_failure!(self.path, - { "a {} pointing to a static variable in a constant", kind } - ); + throw_validation_failure!(self.path, PtrToStatic { ptr_kind }); } // We skip recursively checking other statics. These statics must be sound by // themselves, and the only way to get broken statics here is by using @@ -464,9 +440,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' // This should be unreachable, but if someone manages to copy a pointer // out of a `static`, then that pointer might point to mutable memory, // and we would catch that here. - throw_validation_failure!(self.path, - { "a {} pointing to mutable memory in a constant", kind } - ); + throw_validation_failure!(self.path, PtrToMut { ptr_kind }); } } // Nothing to check for these. @@ -496,22 +470,24 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' let ty = value.layout.ty; match ty.kind() { ty::Bool => { - let value = self.read_scalar(value, "a boolean")?; + let value = self.read_scalar(value, ExpectedKind::Bool)?; try_validation!( value.to_bool(), self.path, - InvalidBool(..) => - { "{:x}", value } expected { "a boolean" }, + InvalidBool(..) => ValidationErrorKind::InvalidBool { + value: format!("{value:x}"), + } ); Ok(true) } ty::Char => { - let value = self.read_scalar(value, "a unicode scalar value")?; + let value = self.read_scalar(value, ExpectedKind::Char)?; try_validation!( value.to_char(), self.path, - InvalidChar(..) => - { "{:x}", value } expected { "a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)" }, + InvalidChar(..) => ValidationErrorKind::InvalidChar { + value: format!("{value:x}"), + } ); Ok(true) } @@ -521,16 +497,17 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' let value = self.read_scalar( value, if matches!(ty.kind(), ty::Float(..)) { - "a floating point number" + ExpectedKind::Float } else { - "an integer" + ExpectedKind::Int }, )?; // As a special exception we *do* match on a `Scalar` here, since we truly want // to know its underlying representation (and *not* cast it to an integer). if matches!(value, Scalar::Ptr(..)) { - throw_validation_failure!(self.path, - { "{:x}", value } expected { "plain (non-pointer) bytes" } + throw_validation_failure!( + self.path, + ExpectedNonPtr { value: format!("{value:x}") } ) } Ok(true) @@ -540,7 +517,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' // actually enforce the strict rules for raw pointers (mostly because // that lets us re-use `ref_to_mplace`). let place = - self.ecx.ref_to_mplace(&self.read_immediate(value, "a raw pointer")?)?; + self.ecx.ref_to_mplace(&self.read_immediate(value, ExpectedKind::RawPtr)?)?; if place.layout.is_unsized() { self.check_wide_ptr_meta(place.meta, place.layout)?; } @@ -554,14 +531,14 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' // a ZST). let layout = self.ecx.layout_of(*ty)?; if !layout.is_zst() { - throw_validation_failure!(self.path, { "mutable reference in a `const`" }); + throw_validation_failure!(self.path, MutableRefInConst); } } - self.check_safe_pointer(value, "reference")?; + self.check_safe_pointer(value, PointerKind::Ref)?; Ok(true) } ty::FnPtr(_sig) => { - let value = self.read_scalar(value, "a function pointer")?; + let value = self.read_scalar(value, ExpectedKind::FnPtr)?; // If we check references recursively, also check that this points to a function. if let Some(_) = self.ref_tracking { @@ -570,19 +547,20 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' self.ecx.get_ptr_fn(ptr), self.path, DanglingIntPointer(..) | - InvalidFunctionPointer(..) => - { "{ptr}" } expected { "a function pointer" }, + InvalidFunctionPointer(..) => InvalidFnPtr { + value: format!("{ptr}"), + }, ); // FIXME: Check if the signature matches } else { // Otherwise (for standalone Miri), we have to still check it to be non-null. if self.ecx.scalar_may_be_null(value)? { - throw_validation_failure!(self.path, { "a null function pointer" }); + throw_validation_failure!(self.path, NullFnPtr); } } Ok(true) } - ty::Never => throw_validation_failure!(self.path, { "a value of the never type `!`" }), + ty::Never => throw_validation_failure!(self.path, NeverVal), ty::Foreign(..) | ty::FnDef(..) => { // Nothing to check. Ok(true) @@ -629,12 +607,9 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' if start == 1 && end == max_value { // Only null is the niche. So make sure the ptr is NOT null. if self.ecx.scalar_may_be_null(scalar)? { - throw_validation_failure!(self.path, - { "a potentially null pointer" } - expected { - "something that cannot possibly fail to be {}", - wrapping_range_format(valid_range, max_value) - } + throw_validation_failure!( + self.path, + NullablePtrOutOfRange { range: valid_range, max_value } ) } else { return Ok(()); @@ -645,12 +620,9 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' } else { // Conservatively, we reject, because the pointer *could* have a bad // value. - throw_validation_failure!(self.path, - { "a pointer" } - expected { - "something that cannot possibly fail to be {}", - wrapping_range_format(valid_range, max_value) - } + throw_validation_failure!( + self.path, + PtrOutOfRange { range: valid_range, max_value } ) } } @@ -659,9 +631,9 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' if valid_range.contains(bits) { Ok(()) } else { - throw_validation_failure!(self.path, - { "{}", bits } - expected { "something {}", wrapping_range_format(valid_range, max_value) } + throw_validation_failure!( + self.path, + OutOfRange { value: format!("{bits}"), range: valid_range, max_value } ) } } @@ -685,10 +657,11 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> Ok(try_validation!( this.ecx.read_discriminant(op), this.path, - InvalidTag(val) => - { "{:x}", val } expected { "a valid enum tag" }, - InvalidUninitBytes(None) => - { "uninitialized bytes" } expected { "a valid enum tag" }, + InvalidTag(val) => InvalidEnumTag { + value: format!("{val:x}"), + }, + + InvalidUninitBytes(None) => UninitEnumTag, ) .1) }) @@ -730,7 +703,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> // Special check preventing `UnsafeCell` inside unions in the inner part of constants. if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) { if !op.layout.ty.is_freeze(*self.ecx.tcx, self.ecx.param_env) { - throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); + throw_validation_failure!(self.path, UnsafeCell); } } Ok(()) @@ -738,7 +711,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> #[inline] fn visit_box(&mut self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> { - self.check_safe_pointer(op, "box")?; + self.check_safe_pointer(op, PointerKind::Box)?; Ok(()) } @@ -756,7 +729,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) && def.is_unsafe_cell() { - throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); + throw_validation_failure!(self.path, UnsafeCell); } } @@ -775,14 +748,13 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> // MyNewtype and then the scalar in there). match op.layout.abi { Abi::Uninhabited => { - throw_validation_failure!(self.path, - { "a value of uninhabited type {:?}", op.layout.ty } - ); + let ty = op.layout.ty; + throw_validation_failure!(self.path, UninhabitedVal { ty }); } Abi::Scalar(scalar_layout) => { if !scalar_layout.is_uninit_valid() { // There is something to check here. - let scalar = self.read_scalar(op, "initialized scalar value")?; + let scalar = self.read_scalar(op, ExpectedKind::InitScalar)?; self.visit_scalar(scalar, scalar_layout)?; } } @@ -792,7 +764,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> // the other must be init. if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() { let (a, b) = - self.read_immediate(op, "initialized scalar value")?.to_scalar_pair(); + self.read_immediate(op, ExpectedKind::InitScalar)?.to_scalar_pair(); self.visit_scalar(a, a_layout)?; self.visit_scalar(b, b_layout)?; } @@ -822,7 +794,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> try_validation!( self.ecx.read_bytes_ptr_strip_provenance(mplace.ptr, Size::from_bytes(len)), self.path, - InvalidUninitBytes(..) => { "uninitialized data in `str`" }, + InvalidUninitBytes(..) => { UninitStr }, ); } ty::Array(tys, ..) | ty::Slice(tys) @@ -852,7 +824,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> Left(mplace) => mplace, Right(imm) => match *imm { Immediate::Uninit => - throw_validation_failure!(self.path, { "uninitialized bytes" }), + throw_validation_failure!(self.path, UninitVal), Immediate::Scalar(..) | Immediate::ScalarPair(..) => bug!("arrays/slices can never have Scalar/ScalarPair layout"), } @@ -888,7 +860,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> .unwrap(); self.path.push(PathElem::ArrayElem(i)); - throw_validation_failure!(self.path, { "uninitialized bytes" }) + throw_validation_failure!(self.path, UninitVal) } // Propagate upwards (that will also check for unexpected errors). @@ -929,12 +901,13 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { match visitor.visit_value(&op) { Ok(()) => Ok(()), // Pass through validation failures. - Err(err) if matches!(err.kind(), err_ub!(ValidationFailure { .. })) => Err(err), + Err(err) if matches!(err.kind(), err_ub!(Validation { .. })) => Err(err), // Complain about any other kind of UB error -- those are bad because we'd like to // report them in a way that shows *where* in the value the issue lies. Err(err) if matches!(err.kind(), InterpError::UndefinedBehavior(_)) => { - err.print_backtrace(); - bug!("Unexpected Undefined Behavior error during validation: {}", err); + let (err, backtrace) = err.into_parts(); + backtrace.print_backtrace(); + bug!("Unexpected Undefined Behavior error during validation: {err:?}"); } // Pass through everything else. Err(err) => Err(err), diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index c36282d5ed442..49248e2af4dfe 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -4,6 +4,7 @@ Rust MIR: a lowered representation of Rust. */ +#![deny(rustc::untranslatable_diagnostic)] #![feature(assert_matches)] #![feature(box_patterns)] #![feature(decl_macro)] diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index 21f3c2c891713..236e43bdfcc71 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -2,9 +2,7 @@ use hir::def_id::LocalDefId; use hir::{ConstContext, LangItem}; -use rustc_errors::{ - error_code, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, -}; +use rustc_errors::{error_code, DiagnosticBuilder, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_infer::infer::TyCtxtInferExt; @@ -152,7 +150,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { if let Ok(Some(ImplSource::UserDefined(data))) = implsrc { let span = tcx.def_span(data.impl_def_id); - err.span_note(span, "impl defined here, but it is not `const`"); + err.subdiagnostic(errors::NonConstImplNote { span }); } } _ => {} @@ -166,26 +164,30 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { let mut err = match call_kind { CallKind::Normal { desugaring: Some((kind, self_ty)), .. } => { macro_rules! error { - ($fmt:literal) => { - struct_span_err!(tcx.sess, span, E0015, $fmt, self_ty, ccx.const_kind()) + ($err:ident) => { + tcx.sess.create_err(errors::$err { + span, + ty: self_ty, + kind: ccx.const_kind(), + }) }; } let mut err = match kind { CallDesugaringKind::ForLoopIntoIter => { - error!("cannot convert `{}` into an iterator in {}s") + error!(NonConstForLoopIntoIter) } CallDesugaringKind::QuestionBranch => { - error!("`?` cannot determine the branch of `{}` in {}s") + error!(NonConstQuestionBranch) } CallDesugaringKind::QuestionFromResidual => { - error!("`?` cannot convert from residual of `{}` in {}s") + error!(NonConstQuestionFromResidual) } CallDesugaringKind::TryBlockFromOutput => { - error!("`try` block cannot convert `{}` to the result in {}s") + error!(NonConstTryBlockFromOutput) } CallDesugaringKind::Await => { - error!("cannot convert `{}` into a future in {}s") + error!(NonConstAwait) } }; @@ -193,49 +195,31 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { err } CallKind::FnCall { fn_trait_id, self_ty } => { - let mut err = struct_span_err!( - tcx.sess, - span, - E0015, - "cannot call non-const closure in {}s", - ccx.const_kind(), - ); - - match self_ty.kind() { + let note = match self_ty.kind() { FnDef(def_id, ..) => { let span = tcx.def_span(*def_id); if ccx.tcx.is_const_fn_raw(*def_id) { span_bug!(span, "calling const FnDef errored when it shouldn't"); } - err.span_note(span, "function defined here, but it is not `const`"); - } - FnPtr(..) => { - err.note(format!( - "function pointers need an RFC before allowed to be called in {}s", - ccx.const_kind() - )); + Some(errors::NonConstClosureNote::FnDef { span }) } - Closure(..) => { - err.note(format!( - "closures need an RFC before allowed to be called in {}s", - ccx.const_kind() - )); - } - _ => {} - } + FnPtr(..) => Some(errors::NonConstClosureNote::FnPtr), + Closure(..) => Some(errors::NonConstClosureNote::Closure), + _ => None, + }; + + let mut err = tcx.sess.create_err(errors::NonConstClosure { + span, + kind: ccx.const_kind(), + note, + }); diag_trait(&mut err, self_ty, fn_trait_id); err } CallKind::Operator { trait_id, self_ty, .. } => { - let mut err = struct_span_err!( - tcx.sess, - span, - E0015, - "cannot call non-const operator in {}s", - ccx.const_kind() - ); + let mut sugg = None; if Some(trait_id) == ccx.tcx.lang_items().eq_trait() { match (substs[0].unpack(), substs[1].unpack()) { @@ -260,14 +244,11 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { let rhs_pos = span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx); let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos); - err.multipart_suggestion( - "consider dereferencing here", - vec![ - (span.shrink_to_lo(), deref.clone()), - (rhs_span, deref), - ], - Applicability::MachineApplicable, - ); + sugg = Some(errors::ConsiderDereferencing { + deref, + span: span.shrink_to_lo(), + rhs_span, + }); } } } @@ -275,26 +256,29 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { _ => {} } } - + let mut err = tcx.sess.create_err(errors::NonConstOperator { + span, + kind: ccx.const_kind(), + sugg, + }); diag_trait(&mut err, self_ty, trait_id); err } CallKind::DerefCoercion { deref_target, deref_target_ty, self_ty } => { - let mut err = struct_span_err!( - tcx.sess, - span, - E0015, - "cannot perform deref coercion on `{}` in {}s", - self_ty, - ccx.const_kind() - ); - - err.note(format!("attempting to deref into `{}`", deref_target_ty)); - // Check first whether the source is accessible (issue #87060) - if tcx.sess.source_map().is_span_accessible(deref_target) { - err.span_note(deref_target, "deref defined here"); - } + let target = if tcx.sess.source_map().is_span_accessible(deref_target) { + Some(deref_target) + } else { + None + }; + + let mut err = tcx.sess.create_err(errors::NonConstDerefCoercion { + span, + ty: self_ty, + kind: ccx.const_kind(), + target_ty: deref_target_ty, + deref_target: target, + }); diag_trait(&mut err, self_ty, tcx.require_lang_item(LangItem::Deref, Some(span))); err @@ -432,21 +416,12 @@ impl<'tcx> NonConstOp<'tcx> for LiveDrop<'tcx> { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - let mut err = struct_span_err!( - ccx.tcx.sess, - span, - E0493, - "destructor of `{}` cannot be evaluated at compile-time", - self.dropped_ty, - ); - err.span_label( + ccx.tcx.sess.create_err(errors::LiveDrop { span, - format!("the destructor for this type cannot be evaluated in {}s", ccx.const_kind()), - ); - if let Some(span) = self.dropped_at { - err.span_label(span, "value is dropped here"); - } - err + dropped_ty: self.dropped_ty, + kind: ccx.const_kind(), + dropped_at: self.dropped_at, + }) } } diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 0accb4ab96f59..b6922282868ae 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -496,6 +496,10 @@ impl MultiSpan { replacements_occurred } + pub fn pop_span_label(&mut self) -> Option<(Span, DiagnosticMessage)> { + self.span_labels.pop() + } + /// Returns the strings to highlight. We always ensure that there /// is an entry for each of the primary spans -- for each primary /// span `P`, if there is at least one label with span `P`, we return diff --git a/compiler/rustc_errors/messages.ftl b/compiler/rustc_errors/messages.ftl index dde1d6c0a819c..5bac7c154823a 100644 --- a/compiler/rustc_errors/messages.ftl +++ b/compiler/rustc_errors/messages.ftl @@ -8,7 +8,11 @@ errors_target_missing_alignment = missing alignment for `{$cause}` in "data-layout" errors_target_invalid_alignment = - invalid alignment for `{$cause}` in "data-layout": {$err} + invalid alignment for `{$cause}` in "data-layout": `{$align}` is {$err_kind -> + [not_power_of_two] not a power of 2 + [too_large] too large + *[other] {""} + } errors_target_inconsistent_architecture = inconsistent target specification: "data-layout" claims architecture is {$dl}-endian, while "target-endian" is `{$target}` diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 29c692128bcf9..8cb005324efc3 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -10,7 +10,7 @@ use rustc_lint_defs::{Applicability, LintExpectationId}; use rustc_span::symbol::Symbol; use rustc_span::{Span, DUMMY_SP}; use std::borrow::Cow; -use std::fmt; +use std::fmt::{self, Debug}; use std::hash::{Hash, Hasher}; use std::panic::Location; @@ -33,7 +33,7 @@ pub type DiagnosticArgName<'source> = Cow<'source, str>; #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)] pub enum DiagnosticArgValue<'source> { Str(Cow<'source, str>), - Number(usize), + Number(i128), StrListSepByAnd(Vec>), } diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index 65f8a61a30a9a..10fe7fc74a873 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -60,10 +60,8 @@ into_diagnostic_arg_using_display!( u8, i16, u16, - i32, u32, i64, - u64, i128, u128, std::io::Error, @@ -80,6 +78,18 @@ into_diagnostic_arg_using_display!( ExitStatus, ); +impl IntoDiagnosticArg for i32 { + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + DiagnosticArgValue::Number(self.into()) + } +} + +impl IntoDiagnosticArg for u64 { + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + DiagnosticArgValue::Number(self.into()) + } +} + impl IntoDiagnosticArg for bool { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { if self { @@ -134,7 +144,7 @@ impl IntoDiagnosticArg for PathBuf { impl IntoDiagnosticArg for usize { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { - DiagnosticArgValue::Number(self) + DiagnosticArgValue::Number(self as i128) } } @@ -147,9 +157,9 @@ impl IntoDiagnosticArg for PanicStrategy { impl IntoDiagnosticArg for hir::ConstContext { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { DiagnosticArgValue::Str(Cow::Borrowed(match self { - hir::ConstContext::ConstFn => "constant function", + hir::ConstContext::ConstFn => "const_fn", hir::ConstContext::Static(_) => "static", - hir::ConstContext::Const => "constant", + hir::ConstContext::Const => "const", })) } } @@ -254,7 +264,8 @@ impl IntoDiagnostic<'_, !> for TargetDataLayoutErrors<'_> { TargetDataLayoutErrors::InvalidAlignment { cause, err } => { diag = handler.struct_fatal(fluent::errors_target_invalid_alignment); diag.set_arg("cause", cause); - diag.set_arg("err", err); + diag.set_arg("err_kind", err.diag_ident()); + diag.set_arg("align", err.align()); diag } TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => { diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index d3495d3dbd71a..b92852a597e2b 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -176,7 +176,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) { } // Generic statics are rejected, but we still reach this case. Err(e) => { - tcx.sess.delay_span_bug(span, e.to_string()); + tcx.sess.delay_span_bug(span, format!("{e:?}")); return; } }; diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index cd6e36874603f..2e6e84ad80eb4 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -14,6 +14,8 @@ use syn::Token; use syn::{parse_quote, spanned::Spanned, Attribute, Meta, Path, Type}; use synstructure::{BindingInfo, Structure, VariantInfo}; +use super::utils::SubdiagnosticVariant; + /// What kind of diagnostic is being derived - a fatal/error/warning or a lint? #[derive(Clone, PartialEq, Eq)] pub(crate) enum DiagnosticDeriveKind { @@ -150,19 +152,19 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { fn parse_subdiag_attribute( &self, attr: &Attribute, - ) -> Result, DiagnosticDeriveError> { - let Some((subdiag, slug)) = SubdiagnosticKind::from_attr(attr, self)? else { + ) -> Result, DiagnosticDeriveError> { + let Some(subdiag) = SubdiagnosticVariant::from_attr(attr, self)? else { // Some attributes aren't errors - like documentation comments - but also aren't // subdiagnostics. return Ok(None); }; - if let SubdiagnosticKind::MultipartSuggestion { .. } = subdiag { + if let SubdiagnosticKind::MultipartSuggestion { .. } = subdiag.kind { throw_invalid_attr!(attr, |diag| diag .help("consider creating a `Subdiagnostic` instead")); } - let slug = slug.unwrap_or_else(|| match subdiag { + let slug = subdiag.slug.unwrap_or_else(|| match subdiag.kind { SubdiagnosticKind::Label => parse_quote! { _subdiag::label }, SubdiagnosticKind::Note => parse_quote! { _subdiag::note }, SubdiagnosticKind::Help => parse_quote! { _subdiag::help }, @@ -171,7 +173,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { SubdiagnosticKind::MultipartSuggestion { .. } => unreachable!(), }); - Ok(Some((subdiag, slug))) + Ok(Some((subdiag.kind, slug, subdiag.no_span))) } /// Establishes state in the `DiagnosticDeriveBuilder` resulting from the struct @@ -229,7 +231,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { return Ok(tokens); } - let Some((subdiag, slug)) = self.parse_subdiag_attribute(attr)? else { + let Some((subdiag, slug, _no_span)) = self.parse_subdiag_attribute(attr)? else { // Some attributes aren't errors - like documentation comments - but also aren't // subdiagnostics. return Ok(quote! {}); @@ -380,7 +382,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { _ => (), } - let Some((subdiag, slug)) = self.parse_subdiag_attribute(attr)? else { + let Some((subdiag, slug, _no_span)) = self.parse_subdiag_attribute(attr)? else { // Some attributes aren't errors - like documentation comments - but also aren't // subdiagnostics. return Ok(quote! {}); diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index 374ba1a45c06e..e3d9eb96574d1 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -14,6 +14,8 @@ use quote::{format_ident, quote}; use syn::{spanned::Spanned, Attribute, Meta, MetaList, Path}; use synstructure::{BindingInfo, Structure, VariantInfo}; +use super::utils::SubdiagnosticVariant; + /// The central struct for constructing the `add_to_diagnostic` method from an annotated struct. pub(crate) struct SubdiagnosticDeriveBuilder { diag: syn::Ident, @@ -180,11 +182,13 @@ impl<'a> FromIterator<&'a SubdiagnosticKind> for KindsStatistics { } impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { - fn identify_kind(&mut self) -> Result, DiagnosticDeriveError> { + fn identify_kind( + &mut self, + ) -> Result, DiagnosticDeriveError> { let mut kind_slugs = vec![]; for attr in self.variant.ast().attrs { - let Some((kind, slug)) = SubdiagnosticKind::from_attr(attr, self)? else { + let Some(SubdiagnosticVariant { kind, slug, no_span }) = SubdiagnosticVariant::from_attr(attr, self)? else { // Some attributes aren't errors - like documentation comments - but also aren't // subdiagnostics. continue; @@ -202,7 +206,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { ); }; - kind_slugs.push((kind, slug)); + kind_slugs.push((kind, slug, no_span)); } Ok(kind_slugs) @@ -487,7 +491,8 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { } }; - let kind_stats: KindsStatistics = kind_slugs.iter().map(|(kind, _slug)| kind).collect(); + let kind_stats: KindsStatistics = + kind_slugs.iter().map(|(kind, _slug, _no_span)| kind).collect(); let init = if kind_stats.has_multipart_suggestion { quote! { let mut suggestions = Vec::new(); } @@ -508,13 +513,17 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { let diag = &self.parent.diag; let f = &self.parent.f; let mut calls = TokenStream::new(); - for (kind, slug) in kind_slugs { + for (kind, slug, no_span) in kind_slugs { let message = format_ident!("__message"); calls.extend( quote! { let #message = #f(#diag, crate::fluent_generated::#slug.into()); }, ); - let name = format_ident!("{}{}", if span_field.is_some() { "span_" } else { "" }, kind); + let name = format_ident!( + "{}{}", + if span_field.is_some() && !no_span { "span_" } else { "" }, + kind + ); let call = match kind { SubdiagnosticKind::Suggestion { suggestion_kind, @@ -566,7 +575,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { } } _ => { - if let Some(span) = span_field { + if let Some(span) = span_field && !no_span { quote! { #diag.#name(#span, #message); } } else { quote! { #diag.#name(#message); } diff --git a/compiler/rustc_macros/src/diagnostics/utils.rs b/compiler/rustc_macros/src/diagnostics/utils.rs index e2434981f8d17..85dd9f6a3ce36 100644 --- a/compiler/rustc_macros/src/diagnostics/utils.rs +++ b/compiler/rustc_macros/src/diagnostics/utils.rs @@ -597,14 +597,20 @@ pub(super) enum SubdiagnosticKind { }, } -impl SubdiagnosticKind { - /// Constructs a `SubdiagnosticKind` from a field or type attribute such as `#[note]`, - /// `#[error(parser::add_paren)]` or `#[suggestion(code = "...")]`. Returns the +pub(super) struct SubdiagnosticVariant { + pub(super) kind: SubdiagnosticKind, + pub(super) slug: Option, + pub(super) no_span: bool, +} + +impl SubdiagnosticVariant { + /// Constructs a `SubdiagnosticVariant` from a field or type attribute such as `#[note]`, + /// `#[error(parser::add_paren, no_span)]` or `#[suggestion(code = "...")]`. Returns the /// `SubdiagnosticKind` and the diagnostic slug, if specified. pub(super) fn from_attr( attr: &Attribute, fields: &impl HasFieldMap, - ) -> Result)>, DiagnosticDeriveError> { + ) -> Result, DiagnosticDeriveError> { // Always allow documentation comments. if is_doc_comment(attr) { return Ok(None); @@ -679,7 +685,7 @@ impl SubdiagnosticKind { | SubdiagnosticKind::Help | SubdiagnosticKind::Warn | SubdiagnosticKind::MultipartSuggestion { .. } => { - return Ok(Some((kind, None))); + return Ok(Some(SubdiagnosticVariant { kind, slug: None, no_span: false })); } SubdiagnosticKind::Suggestion { .. } => { throw_span_err!(span, "suggestion without `code = \"...\"`") @@ -696,11 +702,14 @@ impl SubdiagnosticKind { let mut first = true; let mut slug = None; + let mut no_span = false; list.parse_nested_meta(|nested| { if nested.input.is_empty() || nested.input.peek(Token![,]) { if first { slug = Some(nested.path); + } else if nested.path.is_ident("no_span") { + no_span = true; } else { span_err(nested.input.span().unwrap(), "a diagnostic slug must be the first argument to the attribute").emit(); } @@ -775,19 +784,19 @@ impl SubdiagnosticKind { (_, SubdiagnosticKind::Suggestion { .. }) => { span_err(path_span, "invalid nested attribute") .help( - "only `style`, `code` and `applicability` are valid nested attributes", + "only `no_span`, `style`, `code` and `applicability` are valid nested attributes", ) .emit(); has_errors = true; } (_, SubdiagnosticKind::MultipartSuggestion { .. }) => { span_err(path_span, "invalid nested attribute") - .help("only `style` and `applicability` are valid nested attributes") + .help("only `no_span`, `style` and `applicability` are valid nested attributes") .emit(); has_errors = true; } _ => { - span_err(path_span, "invalid nested attribute").emit(); + span_err(path_span, "only `no_span` is a valid nested attribute").emit(); has_errors = true; } } @@ -831,7 +840,7 @@ impl SubdiagnosticKind { | SubdiagnosticKind::Warn => {} } - Ok(Some((kind, slug))) + Ok(Some(SubdiagnosticVariant { kind, slug, no_span })) } } diff --git a/compiler/rustc_middle/messages.ftl b/compiler/rustc_middle/messages.ftl index 64d511c261aa9..f2249ed48ac33 100644 --- a/compiler/rustc_middle/messages.ftl +++ b/compiler/rustc_middle/messages.ftl @@ -43,3 +43,38 @@ middle_requires_lang_item = requires `{$name}` lang_item middle_const_not_used_in_type_alias = const parameter `{$ct}` is part of concrete type but not used in parameter list for the `impl Trait` type alias + +middle_bounds_check = + index out of bounds: the length is {$len} but the index is {$index} + +middle_assert_overflow_neg = + attempt to negate `{$val}`, which would overflow + +middle_assert_divide_by_zero = + attempt to divide `{$val}` by zero + +middle_assert_remainder_by_zero = + attempt to calculate the remainder of `{$val}` with a divisor of zero + +middle_assert_op_overflow = + attempt to compute `{$left} {$op} {$right}`, which would overflow + +middle_assert_shl_overflow = + attempt to shift left by `{$val}`, which would overflow + +middle_assert_shr_overflow = + attempt to shift right by `{$val}`, which would overflow + +middle_assert_misaligned_ptr_deref = + misaligned pointer dereference: address must be a multiple of {$required} but is {$found} + +middle_assert_generator_resume_after_return = generator resumed after completion + +middle_assert_generator_resume_after_panic = generator resumed after panicking + +middle_assert_async_resume_after_return = `async fn` resumed after completion + +middle_assert_async_resume_after_panic = `async fn` resumed after panicking + +middle_adjust_for_foreign_abi_error = + target architecture {$arch} does not support `extern {$abi}` ABI diff --git a/compiler/rustc_middle/src/error.rs b/compiler/rustc_middle/src/error.rs index 046186d274ca7..57b2de84b47f7 100644 --- a/compiler/rustc_middle/src/error.rs +++ b/compiler/rustc_middle/src/error.rs @@ -1,3 +1,7 @@ +use std::borrow::Cow; +use std::fmt; + +use rustc_errors::{DiagnosticArgValue, DiagnosticMessage}; use rustc_macros::Diagnostic; use rustc_span::{Span, Symbol}; @@ -88,3 +92,54 @@ pub(super) struct ConstNotUsedTraitAlias { #[primary_span] pub span: Span, } + +pub struct CustomSubdiagnostic<'a> { + pub msg: fn() -> DiagnosticMessage, + pub add_args: + Box, DiagnosticArgValue<'static>)) + 'a>, +} + +impl<'a> CustomSubdiagnostic<'a> { + pub fn label(x: fn() -> DiagnosticMessage) -> Self { + Self::label_and_then(x, |_| {}) + } + pub fn label_and_then< + F: FnOnce(&mut dyn FnMut(Cow<'static, str>, DiagnosticArgValue<'static>)) + 'a, + >( + msg: fn() -> DiagnosticMessage, + f: F, + ) -> Self { + Self { msg, add_args: Box::new(move |x| f(x)) } + } +} + +impl fmt::Debug for CustomSubdiagnostic<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CustomSubdiagnostic").finish_non_exhaustive() + } +} + +#[derive(Diagnostic)] +pub enum LayoutError<'tcx> { + #[diag(middle_unknown_layout)] + Unknown { ty: Ty<'tcx> }, + + #[diag(middle_values_too_big)] + Overflow { ty: Ty<'tcx> }, + + #[diag(middle_cannot_be_normalized)] + NormalizationFailure { ty: Ty<'tcx>, failure_ty: String }, + + #[diag(middle_cycle)] + Cycle, +} + +#[derive(Diagnostic)] +#[diag(middle_adjust_for_foreign_abi_error)] +pub struct UnsupportedFnAbi { + pub arch: Symbol, + pub abi: &'static str, +} + +/// Used by `rustc_const_eval` +pub use crate::fluent_generated::middle_adjust_for_foreign_abi_error; diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index 22ee2a8c5e55e..0d6c2eba06c89 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -48,6 +48,7 @@ #![feature(associated_type_bounds)] #![feature(rustc_attrs)] #![feature(control_flow_enum)] +#![feature(trait_upcasting)] #![feature(trusted_step)] #![feature(try_blocks)] #![feature(try_reserve_kind)] @@ -86,7 +87,7 @@ mod macros; #[macro_use] pub mod arena; -pub(crate) mod error; +pub mod error; pub mod hir; pub mod infer; pub mod lint; diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index 1a8e48264471c..b8030d9db13c5 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -296,25 +296,13 @@ impl Allocation { Allocation::from_bytes(slice, Align::ONE, Mutability::Not) } - /// Try to create an Allocation of `size` bytes, failing if there is not enough memory - /// available to the compiler to do so. - /// - /// If `panic_on_fail` is true, this will never return `Err`. - pub fn uninit<'tcx>(size: Size, align: Align, panic_on_fail: bool) -> InterpResult<'tcx, Self> { - let bytes = Bytes::zeroed(size, align).ok_or_else(|| { - // This results in an error that can happen non-deterministically, since the memory - // available to the compiler can change between runs. Normally queries are always - // deterministic. However, we can be non-deterministic here because all uses of const - // evaluation (including ConstProp!) will make compilation fail (via hard error - // or ICE) upon encountering a `MemoryExhausted` error. - if panic_on_fail { - panic!("Allocation::uninit called with panic_on_fail had allocation failure") - } - ty::tls::with(|tcx| { - tcx.sess.delay_span_bug(DUMMY_SP, "exhausted memory during interpretation") - }); - InterpError::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted) - })?; + fn uninit_inner(size: Size, align: Align, fail: impl FnOnce() -> R) -> Result { + // This results in an error that can happen non-deterministically, since the memory + // available to the compiler can change between runs. Normally queries are always + // deterministic. However, we can be non-deterministic here because all uses of const + // evaluation (including ConstProp!) will make compilation fail (via hard error + // or ICE) upon encountering a `MemoryExhausted` error. + let bytes = Bytes::zeroed(size, align).ok_or_else(fail)?; Ok(Allocation { bytes, @@ -325,6 +313,28 @@ impl Allocation { extra: (), }) } + + /// Try to create an Allocation of `size` bytes, failing if there is not enough memory + /// available to the compiler to do so. + pub fn try_uninit<'tcx>(size: Size, align: Align) -> InterpResult<'tcx, Self> { + Self::uninit_inner(size, align, || { + ty::tls::with(|tcx| { + tcx.sess.delay_span_bug(DUMMY_SP, "exhausted memory during interpretation") + }); + InterpError::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted).into() + }) + } + + /// Try to create an Allocation of `size` bytes, panics if there is not enough memory + /// available to the compiler to do so. + pub fn uninit(size: Size, align: Align) -> Self { + match Self::uninit_inner(size, align, || { + panic!("Allocation::uninit called with panic_on_fail had allocation failure"); + }) { + Ok(x) => x, + Err(x) => x, + } + } } impl Allocation { diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 055d8e9a352bc..96e2ab7734971 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -5,11 +5,15 @@ use crate::query::TyCtxtAt; use crate::ty::{layout, tls, Ty, ValTree}; use rustc_data_structures::sync::Lock; -use rustc_errors::{pluralize, struct_span_err, DiagnosticBuilder, ErrorGuaranteed}; +use rustc_errors::{ + struct_span_err, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, + IntoDiagnosticArg, +}; use rustc_macros::HashStable; use rustc_session::CtfeBacktrace; use rustc_span::def_id::DefId; -use rustc_target::abi::{call, Align, Size}; +use rustc_target::abi::{call, Align, Size, WrappingRange}; +use std::borrow::Cow; use std::{any::Any, backtrace::Backtrace, fmt}; #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)] @@ -91,21 +95,54 @@ pub struct InterpErrorInfo<'tcx>(Box>); #[derive(Debug)] struct InterpErrorInfoInner<'tcx> { kind: InterpError<'tcx>, + backtrace: InterpErrorBacktrace, +} + +#[derive(Debug)] +pub struct InterpErrorBacktrace { backtrace: Option>, } -impl fmt::Display for InterpErrorInfo<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0.kind) +impl InterpErrorBacktrace { + pub fn new() -> InterpErrorBacktrace { + let capture_backtrace = tls::with_opt(|tcx| { + if let Some(tcx) = tcx { + *Lock::borrow(&tcx.sess.ctfe_backtrace) + } else { + CtfeBacktrace::Disabled + } + }); + + let backtrace = match capture_backtrace { + CtfeBacktrace::Disabled => None, + CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())), + CtfeBacktrace::Immediate => { + // Print it now. + let backtrace = Backtrace::force_capture(); + print_backtrace(&backtrace); + None + } + }; + + InterpErrorBacktrace { backtrace } } -} -impl<'tcx> InterpErrorInfo<'tcx> { pub fn print_backtrace(&self) { - if let Some(backtrace) = self.0.backtrace.as_ref() { + if let Some(backtrace) = self.backtrace.as_ref() { print_backtrace(backtrace); } } +} + +impl<'tcx> InterpErrorInfo<'tcx> { + pub fn from_parts(kind: InterpError<'tcx>, backtrace: InterpErrorBacktrace) -> Self { + Self(Box::new(InterpErrorInfoInner { kind, backtrace })) + } + + pub fn into_parts(self) -> (InterpError<'tcx>, InterpErrorBacktrace) { + let InterpErrorInfo(box InterpErrorInfoInner { kind, backtrace }) = self; + (kind, backtrace) + } pub fn into_kind(self) -> InterpError<'tcx> { let InterpErrorInfo(box InterpErrorInfoInner { kind, .. }) = self; @@ -130,32 +167,17 @@ impl From for InterpErrorInfo<'_> { impl<'tcx> From> for InterpErrorInfo<'tcx> { fn from(kind: InterpError<'tcx>) -> Self { - let capture_backtrace = tls::with_opt(|tcx| { - if let Some(tcx) = tcx { - *Lock::borrow(&tcx.sess.ctfe_backtrace) - } else { - CtfeBacktrace::Disabled - } - }); - - let backtrace = match capture_backtrace { - CtfeBacktrace::Disabled => None, - CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())), - CtfeBacktrace::Immediate => { - // Print it now. - let backtrace = Backtrace::force_capture(); - print_backtrace(&backtrace); - None - } - }; - - InterpErrorInfo(Box::new(InterpErrorInfoInner { kind, backtrace })) + InterpErrorInfo(Box::new(InterpErrorInfoInner { + kind, + backtrace: InterpErrorBacktrace::new(), + })) } } /// Error information for when the program we executed turned out not to actually be a valid /// program. This cannot happen in stand-alone Miri, but it can happen during CTFE/ConstProp /// where we work on generic code or execution does not have all information available. +#[derive(Debug)] pub enum InvalidProgramInfo<'tcx> { /// Resolution can fail if we are in a too generic context. TooGeneric, @@ -174,25 +196,6 @@ pub enum InvalidProgramInfo<'tcx> { UninitUnsizedLocal, } -impl fmt::Display for InvalidProgramInfo<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use InvalidProgramInfo::*; - match self { - TooGeneric => write!(f, "encountered overly generic constant"), - AlreadyReported(_) => { - write!( - f, - "an error has already been reported elsewhere (this should not usually be printed)" - ) - } - Layout(ref err) => write!(f, "{err}"), - FnAbiAdjustForForeignAbi(ref err) => write!(f, "{err}"), - SizeOfUnsizedType(ty) => write!(f, "size_of called on unsized type `{ty}`"), - UninitUnsizedLocal => write!(f, "unsized local is used while uninitialized"), - } - } -} - /// Details of why a pointer had to be in-bounds. #[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)] pub enum CheckInAllocMsg { @@ -208,26 +211,25 @@ pub enum CheckInAllocMsg { InboundsTest, } -impl fmt::Display for CheckInAllocMsg { - /// When this is printed as an error the context looks like this: - /// "{msg}{pointer} is a dangling pointer". - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}", - match *self { - CheckInAllocMsg::DerefTest => "dereferencing pointer failed: ", - CheckInAllocMsg::MemoryAccessTest => "memory access failed: ", - CheckInAllocMsg::PointerArithmeticTest => "out-of-bounds pointer arithmetic: ", - CheckInAllocMsg::OffsetFromTest => "out-of-bounds offset_from: ", - CheckInAllocMsg::InboundsTest => "out-of-bounds pointer use: ", - } - ) +#[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)] +pub enum InvalidMetaKind { + /// Size of a `[T]` is too big + SliceTooBig, + /// Size of a DST is too big + TooBig, +} + +impl IntoDiagnosticArg for InvalidMetaKind { + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + DiagnosticArgValue::Str(Cow::Borrowed(match self { + InvalidMetaKind::SliceTooBig => "slice_too_big", + InvalidMetaKind::TooBig => "too_big", + })) } } /// Details of an access to uninitialized bytes where it is not allowed. -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub struct UninitBytesAccess { /// Range of the original memory access. pub access: AllocRange, @@ -242,9 +244,26 @@ pub struct ScalarSizeMismatch { pub data_size: u64, } +macro_rules! impl_into_diagnostic_arg_through_debug { + ($($ty:ty),*$(,)?) => {$( + impl IntoDiagnosticArg for $ty { + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + DiagnosticArgValue::Str(Cow::Owned(format!("{self:?}"))) + } + } + )*} +} + +impl_into_diagnostic_arg_through_debug! { + AllocId, + Pointer, + AllocRange, +} + /// Error information for when the program caused Undefined Behavior. -pub enum UndefinedBehaviorInfo { - /// Free-form case. Only for errors that are never caught! +#[derive(Debug)] +pub enum UndefinedBehaviorInfo<'a> { + /// Free-form case. Only for errors that are never caught! Used by miri Ub(String), /// Unreachable code was executed. Unreachable, @@ -263,8 +282,8 @@ pub enum UndefinedBehaviorInfo { RemainderOverflow, /// Overflowing inbounds pointer arithmetic. PointerArithOverflow, - /// Invalid metadata in a wide pointer (using `str` to avoid allocations). - InvalidMeta(&'static str), + /// Invalid metadata in a wide pointer + InvalidMeta(InvalidMetaKind), /// Reading a C string that does not end within its allocation. UnterminatedCString(Pointer), /// Dereferencing a dangling pointer after it got freed. @@ -287,19 +306,10 @@ pub enum UndefinedBehaviorInfo { }, /// Writing to read-only memory. WriteToReadOnly(AllocId), - // Trying to access the data behind a function pointer. + /// Trying to access the data behind a function pointer. DerefFunctionPointer(AllocId), - // Trying to access the data behind a vtable pointer. + /// Trying to access the data behind a vtable pointer. DerefVTablePointer(AllocId), - /// The value validity check found a problem. - /// Should only be thrown by `validity.rs` and always point out which part of the value - /// is the problem. - ValidationFailure { - /// The "path" to the value in question, e.g. `.0[5].field` for a struct - /// field in the 6th element of an array that is the first element of a tuple. - path: Option, - msg: String, - }, /// Using a non-boolean `u8` as bool. InvalidBool(u8), /// Using a non-character `u32` as character. @@ -320,110 +330,97 @@ pub enum UndefinedBehaviorInfo { ScalarSizeMismatch(ScalarSizeMismatch), /// A discriminant of an uninhabited enum variant is written. UninhabitedEnumVariantWritten, + /// Validation error. + Validation(ValidationErrorInfo<'a>), + Custom(crate::error::CustomSubdiagnostic<'a>), } -impl fmt::Display for UndefinedBehaviorInfo { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use UndefinedBehaviorInfo::*; - match self { - Ub(msg) => write!(f, "{msg}"), - Unreachable => write!(f, "entering unreachable code"), - BoundsCheckFailed { ref len, ref index } => { - write!(f, "indexing out of bounds: the len is {len} but the index is {index}") - } - DivisionByZero => write!(f, "dividing by zero"), - RemainderByZero => write!(f, "calculating the remainder with a divisor of zero"), - DivisionOverflow => write!(f, "overflow in signed division (dividing MIN by -1)"), - RemainderOverflow => write!(f, "overflow in signed remainder (dividing MIN by -1)"), - PointerArithOverflow => write!(f, "overflowing in-bounds pointer arithmetic"), - InvalidMeta(msg) => write!(f, "invalid metadata in wide pointer: {msg}"), - UnterminatedCString(p) => write!( - f, - "reading a null-terminated string starting at {p:?} with no null found before end of allocation", - ), - PointerUseAfterFree(a) => { - write!(f, "pointer to {a:?} was dereferenced after this allocation got freed") - } - PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size: Size::ZERO, msg } => { - write!( - f, - "{msg}{alloc_id:?} has size {alloc_size}, so pointer at offset {ptr_offset} is out-of-bounds", - alloc_size = alloc_size.bytes(), - ) - } - PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => write!( - f, - "{msg}{alloc_id:?} has size {alloc_size}, so pointer to {ptr_size} byte{ptr_size_p} starting at offset {ptr_offset} is out-of-bounds", - alloc_size = alloc_size.bytes(), - ptr_size = ptr_size.bytes(), - ptr_size_p = pluralize!(ptr_size.bytes()), - ), - DanglingIntPointer(i, msg) => { - write!( - f, - "{msg}{pointer} is a dangling pointer (it has no provenance)", - pointer = Pointer::>::from_addr_invalid(*i), - ) - } - AlignmentCheckFailed { required, has } => write!( - f, - "accessing memory with alignment {has}, but alignment {required} is required", - has = has.bytes(), - required = required.bytes() - ), - WriteToReadOnly(a) => write!(f, "writing to {a:?} which is read-only"), - DerefFunctionPointer(a) => write!(f, "accessing {a:?} which contains a function"), - DerefVTablePointer(a) => write!(f, "accessing {a:?} which contains a vtable"), - ValidationFailure { path: None, msg } => { - write!(f, "constructing invalid value: {msg}") - } - ValidationFailure { path: Some(path), msg } => { - write!(f, "constructing invalid value at {path}: {msg}") - } - InvalidBool(b) => { - write!(f, "interpreting an invalid 8-bit value as a bool: 0x{b:02x}") - } - InvalidChar(c) => { - write!(f, "interpreting an invalid 32-bit value as a char: 0x{c:08x}") - } - InvalidTag(val) => write!(f, "enum value has invalid tag: {val:x}"), - InvalidFunctionPointer(p) => { - write!(f, "using {p:?} as function pointer but it does not point to a function") - } - InvalidVTablePointer(p) => { - write!(f, "using {p:?} as vtable pointer but it does not point to a vtable") - } - InvalidStr(err) => write!(f, "this string is not valid UTF-8: {err}"), - InvalidUninitBytes(Some((alloc, info))) => write!( - f, - "reading memory at {alloc:?}{access:?}, \ - but memory is uninitialized at {uninit:?}, \ - and this operation requires initialized memory", - access = info.access, - uninit = info.uninit, - ), - InvalidUninitBytes(None) => write!( - f, - "using uninitialized data, but this operation requires initialized memory" - ), - DeadLocal => write!(f, "accessing a dead local variable"), - ScalarSizeMismatch(self::ScalarSizeMismatch { target_size, data_size }) => write!( - f, - "scalar size mismatch: expected {target_size} bytes but got {data_size} bytes instead", - ), - UninhabitedEnumVariantWritten => { - write!(f, "writing discriminant of an uninhabited enum") +#[derive(Debug, Clone, Copy)] +pub enum PointerKind { + Ref, + Box, +} + +impl IntoDiagnosticArg for PointerKind { + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + DiagnosticArgValue::Str( + match self { + Self::Ref => "ref", + Self::Box => "box", } + .into(), + ) + } +} + +#[derive(Debug)] +pub struct ValidationErrorInfo<'tcx> { + pub path: Option, + pub kind: ValidationErrorKind<'tcx>, +} + +#[derive(Debug)] +pub enum ExpectedKind { + Reference, + Box, + RawPtr, + InitScalar, + Bool, + Char, + Float, + Int, + FnPtr, +} + +impl From for ExpectedKind { + fn from(x: PointerKind) -> ExpectedKind { + match x { + PointerKind::Box => ExpectedKind::Box, + PointerKind::Ref => ExpectedKind::Reference, } } } +#[derive(Debug)] +pub enum ValidationErrorKind<'tcx> { + PtrToUninhabited { ptr_kind: PointerKind, ty: Ty<'tcx> }, + PtrToStatic { ptr_kind: PointerKind }, + PtrToMut { ptr_kind: PointerKind }, + ExpectedNonPtr { value: String }, + MutableRefInConst, + NullFnPtr, + NeverVal, + NullablePtrOutOfRange { range: WrappingRange, max_value: u128 }, + PtrOutOfRange { range: WrappingRange, max_value: u128 }, + OutOfRange { value: String, range: WrappingRange, max_value: u128 }, + UnsafeCell, + UninhabitedVal { ty: Ty<'tcx> }, + InvalidEnumTag { value: String }, + UninitEnumTag, + UninitStr, + Uninit { expected: ExpectedKind }, + UninitVal, + InvalidVTablePtr { value: String }, + InvalidMetaSliceTooLarge { ptr_kind: PointerKind }, + InvalidMetaTooLarge { ptr_kind: PointerKind }, + UnalignedPtr { ptr_kind: PointerKind, required_bytes: u64, found_bytes: u64 }, + NullPtr { ptr_kind: PointerKind }, + DanglingPtrNoProvenance { ptr_kind: PointerKind, pointer: String }, + DanglingPtrOutOfBounds { ptr_kind: PointerKind }, + DanglingPtrUseAfterFree { ptr_kind: PointerKind }, + InvalidBool { value: String }, + InvalidChar { value: String }, + InvalidFnPtr { value: String }, +} + /// Error information for when the program did something that might (or might not) be correct /// to do according to the Rust spec, but due to limitations in the interpreter, the /// operation could not be carried out. These limitations can differ between CTFE and the /// Miri engine, e.g., CTFE does not support dereferencing pointers at integral addresses. +#[derive(Debug)] pub enum UnsupportedOpInfo { /// Free-form case. Only for errors that are never caught! + // FIXME still use translatable diagnostics Unsupported(String), // // The variants below are only reachable from CTFE/const prop, miri will never emit them. @@ -442,26 +439,9 @@ pub enum UnsupportedOpInfo { ReadExternStatic(DefId), } -impl fmt::Display for UnsupportedOpInfo { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use UnsupportedOpInfo::*; - match self { - Unsupported(ref msg) => write!(f, "{msg}"), - PartialPointerOverwrite(ptr) => { - write!(f, "unable to overwrite parts of a pointer in memory at {ptr:?}") - } - PartialPointerCopy(ptr) => { - write!(f, "unable to copy parts of a pointer from memory at {ptr:?}") - } - ReadPointerAsBytes => write!(f, "unable to turn pointer into raw bytes"), - ThreadLocalStatic(did) => write!(f, "cannot access thread local static ({did:?})"), - ReadExternStatic(did) => write!(f, "cannot read from extern static ({did:?})"), - } - } -} - /// Error information for when the program exhausted the resources granted to it /// by the interpreter. +#[derive(Debug)] pub enum ResourceExhaustionInfo { /// The stack grew too big. StackFrameLimitReached, @@ -474,51 +454,26 @@ pub enum ResourceExhaustionInfo { /// The address space (of the target) is full. AddressSpaceFull, } - -impl fmt::Display for ResourceExhaustionInfo { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use ResourceExhaustionInfo::*; - match self { - StackFrameLimitReached => { - write!(f, "reached the configured maximum number of stack frames") - } - StepLimitReached => { - write!(f, "exceeded interpreter step limit (see `#[const_eval_limit]`)") - } - MemoryExhausted => { - write!(f, "tried to allocate more memory than available to compiler") - } - AddressSpaceFull => { - write!(f, "there are no more free addresses in the address space") - } - } - } -} - -/// A trait to work around not having trait object upcasting. -pub trait AsAny: Any { - fn as_any(&self) -> &dyn Any; -} -impl AsAny for T { - #[inline(always)] - fn as_any(&self) -> &dyn Any { - self - } -} - /// A trait for machine-specific errors (or other "machine stop" conditions). -pub trait MachineStopType: AsAny + fmt::Display + Send {} +pub trait MachineStopType: Any + fmt::Debug + Send { + fn diagnostic_message(&self) -> DiagnosticMessage; + fn add_args( + self: Box, + adder: &mut dyn FnMut(Cow<'static, str>, DiagnosticArgValue<'static>), + ); +} impl dyn MachineStopType { #[inline(always)] pub fn downcast_ref(&self) -> Option<&T> { - self.as_any().downcast_ref() + let x: &dyn Any = self; + x.downcast_ref() } } pub enum InterpError<'tcx> { /// The program caused undefined behavior. - UndefinedBehavior(UndefinedBehaviorInfo), + UndefinedBehavior(UndefinedBehaviorInfo<'tcx>), /// The program did something the interpreter does not support (some of these *might* be UB /// but the interpreter is not sure). Unsupported(UnsupportedOpInfo), @@ -534,26 +489,19 @@ pub enum InterpError<'tcx> { pub type InterpResult<'tcx, T = ()> = Result>; -impl fmt::Display for InterpError<'_> { +impl fmt::Debug for InterpError<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use InterpError::*; - match *self { - Unsupported(ref msg) => write!(f, "{msg}"), - InvalidProgram(ref msg) => write!(f, "{msg}"), - UndefinedBehavior(ref msg) => write!(f, "{msg}"), - ResourceExhaustion(ref msg) => write!(f, "{msg}"), - MachineStop(ref msg) => write!(f, "{msg}"), + match self { + Unsupported(msg) => msg.fmt(f), + InvalidProgram(msg) => msg.fmt(f), + UndefinedBehavior(msg) => msg.fmt(f), + ResourceExhaustion(msg) => msg.fmt(f), + MachineStop(msg) => msg.fmt(f), } } } -// Forward `Debug` to `Display`, so it does not look awful. -impl fmt::Debug for InterpError<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - impl InterpError<'_> { /// Some errors do string formatting even if the error is never printed. /// To avoid performance issues, there are places where we want to be sure to never raise these formatting errors, @@ -562,7 +510,7 @@ impl InterpError<'_> { matches!( self, InterpError::Unsupported(UnsupportedOpInfo::Unsupported(_)) - | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::ValidationFailure { .. }) + | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Validation { .. }) | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_)) ) } diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 3620385fab134..cc9a86127cd2b 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -34,7 +34,11 @@ macro_rules! err_ub { #[macro_export] macro_rules! err_ub_format { - ($($tt:tt)*) => { err_ub!(Ub(format!($($tt)*))) }; + ($msg:expr $(, $($tt:tt)* )?) => {{ + err_ub!(Ub( + format!($msg $( , $($tt)* )?) + )) + }}; } #[macro_export] @@ -74,6 +78,11 @@ macro_rules! throw_ub { ($($tt:tt)*) => { do yeet err_ub!($($tt)*) }; } +#[macro_export] +macro_rules! throw_ub_diag { + ($($tt:tt)*) => { do yeet err_ub_format!($($tt)*) }; +} + #[macro_export] macro_rules! throw_ub_format { ($($tt:tt)*) => { throw_ub!(Ub(format!($($tt)*))) }; @@ -89,6 +98,30 @@ macro_rules! throw_machine_stop { ($($tt:tt)*) => { do yeet err_machine_stop!($($tt)*) }; } +#[macro_export] +macro_rules! err_ub_custom { + ($msg:expr $(, $($name:ident = $value:expr),* $(,)?)?) => {{ + $( + let ($($name,)*) = ($($value,)*); + )? + err_ub!(Custom( + rustc_middle::error::CustomSubdiagnostic { + msg: || $msg, + add_args: Box::new(move |mut set_arg| { + $($( + set_arg(stringify!($name).into(), rustc_errors::IntoDiagnosticArg::into_diagnostic_arg($name)); + )*)? + }) + } + )) + }}; +} + +#[macro_export] +macro_rules! throw_ub_custom { + ($($tt:tt)*) => { do yeet err_ub_custom!($($tt)*) }; +} + mod allocation; mod error; mod pointer; @@ -119,9 +152,10 @@ use crate::ty::{self, Instance, Ty, TyCtxt}; pub use self::error::{ struct_error, CheckInAllocMsg, ErrorHandled, EvalToAllocationRawResult, EvalToConstValueResult, - EvalToValTreeResult, InterpError, InterpErrorInfo, InterpResult, InvalidProgramInfo, - MachineStopType, ReportedErrorInfo, ResourceExhaustionInfo, ScalarSizeMismatch, - UndefinedBehaviorInfo, UninitBytesAccess, UnsupportedOpInfo, + EvalToValTreeResult, ExpectedKind, InterpError, InterpErrorInfo, InterpResult, InvalidMetaKind, + InvalidProgramInfo, MachineStopType, PointerKind, ReportedErrorInfo, ResourceExhaustionInfo, + ScalarSizeMismatch, UndefinedBehaviorInfo, UninitBytesAccess, UnsupportedOpInfo, + ValidationErrorInfo, ValidationErrorKind, }; pub use self::value::{get_slice_bytes, ConstAlloc, ConstValue, Scalar}; diff --git a/compiler/rustc_middle/src/mir/interpret/value.rs b/compiler/rustc_middle/src/mir/interpret/value.rs index 36dbbe4bf7765..91caf9db336cf 100644 --- a/compiler/rustc_middle/src/mir/interpret/value.rs +++ b/compiler/rustc_middle/src/mir/interpret/value.rs @@ -375,7 +375,8 @@ impl<'tcx, Prov: Provenance> Scalar { #[inline(always)] #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980) pub fn assert_bits(self, target_size: Size) -> u128 { - self.to_bits(target_size).unwrap() + self.to_bits(target_size) + .unwrap_or_else(|_| panic!("assertion failed: {self:?} fits {target_size:?}")) } pub fn to_bool(self) -> InterpResult<'tcx, bool> { diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 5c71910a955d8..c307f7efd9621 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -15,7 +15,7 @@ use crate::ty::{AdtDef, InstanceDef, ScalarInt, UserTypeAnnotationIndex}; use crate::ty::{GenericArg, InternalSubsts, SubstsRef}; use rustc_data_structures::captures::Captures; -use rustc_errors::ErrorGuaranteed; +use rustc_errors::{DiagnosticArgValue, DiagnosticMessage, ErrorGuaranteed, IntoDiagnosticArg}; use rustc_hir::def::{CtorKind, Namespace}; use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_hir::{self, GeneratorKind, ImplicitSelfKind}; @@ -1371,55 +1371,61 @@ impl AssertKind { _ => write!(f, "\"{}\"", self.description()), } } -} -impl fmt::Debug for AssertKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + pub fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; use AssertKind::*; + match self { - BoundsCheck { ref len, ref index } => write!( - f, - "index out of bounds: the length is {:?} but the index is {:?}", - len, index - ), - OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op), - DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op), - RemainderByZero(op) => write!( - f, - "attempt to calculate the remainder of `{:#?}` with a divisor of zero", - op - ), - Overflow(BinOp::Add, l, r) => { - write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r) - } - Overflow(BinOp::Sub, l, r) => { - write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r) - } - Overflow(BinOp::Mul, l, r) => { - write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r) - } - Overflow(BinOp::Div, l, r) => { - write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r) + BoundsCheck { .. } => middle_bounds_check, + Overflow(BinOp::Shl, _, _) => middle_assert_shl_overflow, + Overflow(BinOp::Shr, _, _) => middle_assert_shr_overflow, + Overflow(_, _, _) => middle_assert_op_overflow, + OverflowNeg(_) => middle_assert_overflow_neg, + DivisionByZero(_) => middle_assert_divide_by_zero, + RemainderByZero(_) => middle_assert_remainder_by_zero, + ResumedAfterReturn(GeneratorKind::Async(_)) => middle_assert_async_resume_after_return, + ResumedAfterReturn(GeneratorKind::Gen) => middle_assert_generator_resume_after_return, + ResumedAfterPanic(GeneratorKind::Async(_)) => middle_assert_async_resume_after_panic, + ResumedAfterPanic(GeneratorKind::Gen) => middle_assert_generator_resume_after_panic, + + MisalignedPointerDereference { .. } => middle_assert_misaligned_ptr_deref, + } + } + + pub fn add_args(self, adder: &mut dyn FnMut(Cow<'static, str>, DiagnosticArgValue<'static>)) + where + O: fmt::Debug, + { + use AssertKind::*; + + macro_rules! add { + ($name: expr, $value: expr) => { + adder($name.into(), $value.into_diagnostic_arg()); + }; + } + + match self { + BoundsCheck { len, index } => { + add!("len", format!("{len:?}")); + add!("index", format!("{index:?}")); } - Overflow(BinOp::Rem, l, r) => write!( - f, - "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow", - l, r - ), - Overflow(BinOp::Shr, _, r) => { - write!(f, "attempt to shift right by `{:#?}`, which would overflow", r) + Overflow(BinOp::Shl | BinOp::Shr, _, val) + | DivisionByZero(val) + | RemainderByZero(val) + | OverflowNeg(val) => { + add!("val", format!("{val:#?}")); } - Overflow(BinOp::Shl, _, r) => { - write!(f, "attempt to shift left by `{:#?}`, which would overflow", r) + Overflow(binop, left, right) => { + add!("op", binop.to_hir_binop().as_str()); + add!("left", format!("{left:#?}")); + add!("right", format!("{right:#?}")); } + ResumedAfterReturn(_) | ResumedAfterPanic(_) => {} MisalignedPointerDereference { required, found } => { - write!( - f, - "misaligned pointer dereference: address must be a multiple of {:?} but is {:?}", - required, found - ) + add!("required", format!("{required:#?}")); + add!("found", format!("{found:#?}")); } - _ => write!(f, "{}", self.description()), } } } diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 62c3d8cf23913..8477722ea393c 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -846,7 +846,7 @@ fn write_allocation_newline( /// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there /// is only one line). Note that your prefix should contain a trailing space as the lines are /// printed directly after it. -fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( +pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( tcx: TyCtxt<'tcx>, alloc: &Allocation, w: &mut dyn std::fmt::Write, diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 21faf1958e911..cdcccae794508 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -792,7 +792,8 @@ pub enum UnwindAction { } /// Information about an assertion failure. -#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)] +#[derive(Clone, Hash, HashStable, PartialEq, Debug)] +#[derive(TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)] pub enum AssertKind { BoundsCheck { len: O, index: O }, Overflow(BinOp, O, O), diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index d1dbc531edfc1..1e43fab457e56 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -1,5 +1,6 @@ use rustc_apfloat::ieee::{Double, Single}; use rustc_apfloat::Float; +use rustc_errors::{DiagnosticArgValue, IntoDiagnosticArg}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::Size; use std::fmt; @@ -113,6 +114,14 @@ impl std::fmt::Debug for ConstInt { } } +impl IntoDiagnosticArg for ConstInt { + // FIXME this simply uses the Debug impl, but we could probably do better by converting both + // to an inherent method that returns `Cow`. + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + DiagnosticArgValue::Str(format!("{self:?}").into()) + } +} + /// The raw bytes of a simple value. /// /// This is a packed struct in order to allow this type to be optimally embedded in enums diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index b5a743cfe343e..c5a306fdf1f9a 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -1,8 +1,9 @@ -use crate::fluent_generated as fluent; +use crate::error::UnsupportedFnAbi; use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::query::TyCtxtAt; use crate::ty::normalize_erasing_regions::NormalizationError; use crate::ty::{self, ReprOptions, Ty, TyCtxt, TypeVisitableExt}; +use rustc_error_messages::DiagnosticMessage; use rustc_errors::{DiagnosticBuilder, Handler, IntoDiagnostic}; use rustc_hir as hir; use rustc_hir::def_id::DefId; @@ -14,7 +15,7 @@ use rustc_target::abi::call::FnAbi; use rustc_target::abi::*; use rustc_target::spec::{abi::Abi as SpecAbi, HasTargetSpec, PanicStrategy, Target}; -use std::cmp::{self}; +use std::cmp; use std::fmt; use std::num::NonZeroUsize; use std::ops::Bound; @@ -214,29 +215,29 @@ pub enum LayoutError<'tcx> { Cycle, } -impl IntoDiagnostic<'_, !> for LayoutError<'_> { - fn into_diagnostic(self, handler: &Handler) -> DiagnosticBuilder<'_, !> { - let mut diag = handler.struct_fatal(""); +impl<'tcx> LayoutError<'tcx> { + pub fn diagnostic_message(&self) -> DiagnosticMessage { + use crate::fluent_generated::*; + use LayoutError::*; + match self { + Unknown(_) => middle_unknown_layout, + SizeOverflow(_) => middle_values_too_big, + NormalizationFailure(_, _) => middle_cannot_be_normalized, + Cycle => middle_cycle, + } + } + pub fn into_diagnostic(self) -> crate::error::LayoutError<'tcx> { + use crate::error::LayoutError as E; + use LayoutError::*; match self { - LayoutError::Unknown(ty) => { - diag.set_arg("ty", ty); - diag.set_primary_message(fluent::middle_unknown_layout); - } - LayoutError::SizeOverflow(ty) => { - diag.set_arg("ty", ty); - diag.set_primary_message(fluent::middle_values_too_big); - } - LayoutError::NormalizationFailure(ty, e) => { - diag.set_arg("ty", ty); - diag.set_arg("failure_ty", e.get_type_for_failure()); - diag.set_primary_message(fluent::middle_cannot_be_normalized); - } - LayoutError::Cycle => { - diag.set_primary_message(fluent::middle_cycle); + Unknown(ty) => E::Unknown { ty }, + SizeOverflow(ty) => E::Overflow { ty }, + NormalizationFailure(ty, e) => { + E::NormalizationFailure { ty, failure_ty: e.get_type_for_failure() } } + Cycle => E::Cycle, } - diag } } @@ -330,11 +331,8 @@ impl<'tcx> SizeSkeleton<'tcx> { Ok(SizeSkeleton::Pointer { non_zero, tail: tcx.erase_regions(tail) }) } _ => bug!( - "SizeSkeleton::compute({}): layout errored ({}), yet \ - tail `{}` is not a type parameter or a projection", - ty, - err, - tail + "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \ + tail `{tail}` is not a type parameter or a projection", ), } } @@ -940,12 +938,8 @@ where TyMaybeWithLayout::Ty(field_ty) => { cx.tcx().layout_of(cx.param_env().and(field_ty)).unwrap_or_else(|e| { bug!( - "failed to get layout for `{}`: {},\n\ - despite it being a field (#{}) of an existing layout: {:#?}", - field_ty, - e, - i, - this + "failed to get layout for `{field_ty}`: {e:?},\n\ + despite it being a field (#{i}) of an existing layout: {this:#?}", ) }) } @@ -1262,21 +1256,18 @@ impl From for FnAbiError<'_> { } } -impl<'tcx> fmt::Display for FnAbiError<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl<'a, 'b> IntoDiagnostic<'a, !> for FnAbiError<'b> { + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, !> { match self { - Self::Layout(err) => err.fmt(f), - Self::AdjustForForeignAbi(err) => err.fmt(f), + Self::Layout(e) => e.into_diagnostic().into_diagnostic(handler), + Self::AdjustForForeignAbi(call::AdjustForForeignAbiError::Unsupported { + arch, + abi, + }) => UnsupportedFnAbi { arch, abi: abi.name() }.into_diagnostic(handler), } } } -impl IntoDiagnostic<'_, !> for FnAbiError<'_> { - fn into_diagnostic(self, handler: &Handler) -> DiagnosticBuilder<'_, !> { - handler.struct_fatal(self.to_string()) - } -} - // FIXME(eddyb) maybe use something like this for an unified `fn_abi_of`, not // just for error handling. #[derive(Debug)] diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index b9b1cd73a8b9a..443791d0af4ba 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -73,7 +73,7 @@ pub(super) fn vtable_allocation_provider<'tcx>( let ptr_align = tcx.data_layout.pointer_align.abi; let vtable_size = ptr_size * u64::try_from(vtable_entries.len()).unwrap(); - let mut vtable = Allocation::uninit(vtable_size, ptr_align, /* panic_on_fail */ true).unwrap(); + let mut vtable = Allocation::uninit(vtable_size, ptr_align); // No need to do any alignment checks on the memory accesses below, because we know the // allocation is correctly aligned as we created it above. Also we're only offsetting by diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index a5d18fff89bd7..5e159102c497d 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -37,6 +37,7 @@ macro_rules! throw_machine_stop_str { ($($tt:tt)*) => {{ // We make a new local type for it. The type itself does not carry any information, // but its vtable (for the `MachineStopType` trait) does. + #[derive(Debug)] struct Zst; // Printing this type shows the desired string. impl std::fmt::Display for Zst { @@ -44,7 +45,17 @@ macro_rules! throw_machine_stop_str { write!(f, $($tt)*) } } - impl rustc_middle::mir::interpret::MachineStopType for Zst {} + + impl rustc_middle::mir::interpret::MachineStopType for Zst { + fn diagnostic_message(&self) -> rustc_errors::DiagnosticMessage { + self.to_string().into() + } + + fn add_args( + self: Box, + _: &mut dyn FnMut(std::borrow::Cow<'static, str>, rustc_errors::DiagnosticArgValue<'static>), + ) {} + } throw_machine_stop!(Zst) }}; } @@ -367,7 +378,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { op } Err(e) => { - trace!("get_const failed: {}", e); + trace!("get_const failed: {e:?}"); return None; } }; diff --git a/compiler/rustc_mir_transform/src/const_prop_lint.rs b/compiler/rustc_mir_transform/src/const_prop_lint.rs index adb09c509d287..9a48e6671d31c 100644 --- a/compiler/rustc_mir_transform/src/const_prop_lint.rs +++ b/compiler/rustc_mir_transform/src/const_prop_lint.rs @@ -232,7 +232,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { op } Err(e) => { - trace!("get_const failed: {}", e); + trace!("get_const failed: {e:?}"); return None; } }; @@ -267,14 +267,6 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { Ok(val) => Some(val), Err(error) => { trace!("InterpCx operation failed: {:?}", error); - // Some errors shouldn't come up because creating them causes - // an allocation, which we should avoid. When that happens, - // dedicated error variants should be introduced instead. - assert!( - !error.kind().formatted_string(), - "const-prop encountered formatting error: {}", - error - ); None } } diff --git a/compiler/rustc_mir_transform/src/errors.rs b/compiler/rustc_mir_transform/src/errors.rs index 602e40d513104..22f71bb08516c 100644 --- a/compiler/rustc_mir_transform/src/errors.rs +++ b/compiler/rustc_mir_transform/src/errors.rs @@ -163,7 +163,14 @@ impl<'a, P: std::fmt::Debug> DecorateLint<'a, ()> for AssertLint

{ self, diag: &'b mut DiagnosticBuilder<'a, ()>, ) -> &'b mut DiagnosticBuilder<'a, ()> { - diag.span_label(self.span(), format!("{:?}", self.panic())); + let span = self.span(); + let assert_kind = self.panic(); + let message = assert_kind.diagnostic_message(); + assert_kind.add_args(&mut |name, value| { + diag.set_arg(name, value); + }); + diag.span_label(span, message); + diag } @@ -191,7 +198,7 @@ impl

AssertLint

{ AssertLint::ArithmeticOverflow(sp, _) | AssertLint::UnconditionalPanic(sp, _) => *sp, } } - pub fn panic(&self) -> &AssertKind

{ + pub fn panic(self) -> AssertKind

{ match self { AssertLint::ArithmeticOverflow(_, p) | AssertLint::UnconditionalPanic(_, p) => p, } diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 5a1ae808e661a..854d45ab483f2 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -93,7 +93,7 @@ fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribute) { Err(layout_error) => { tcx.sess.emit_fatal(Spanned { - node: layout_error, + node: layout_error.into_diagnostic(), span: tcx.def_span(item_def_id.to_def_id()), }); } @@ -109,12 +109,7 @@ impl<'tcx> LayoutOfHelpers<'tcx> for UnwrapLayoutCx<'tcx> { type LayoutOfResult = TyAndLayout<'tcx>; fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { - span_bug!( - span, - "`#[rustc_layout(..)]` test resulted in `layout_of({}) = Err({})`", - ty, - err - ); + span_bug!(span, "`#[rustc_layout(..)]` test resulted in `layout_of({ty}) = Err({err:?})`",); } } diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index da8a16dee8ac7..7469d1f316162 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -502,7 +502,15 @@ fn encode_ty<'tcx>( ty::Array(ty0, len) => { // A let mut s = String::from("A"); - let _ = write!(s, "{}", &len.kind().try_to_scalar().unwrap().to_u64().unwrap()); + let _ = write!( + s, + "{}", + &len.kind() + .try_to_scalar() + .unwrap() + .to_u64() + .unwrap_or_else(|_| panic!("failed to convert length to u64")) + ); s.push_str(&encode_ty(tcx, *ty0, dict, options)); compress(dict, DictKey::Ty(ty, TyQ::None), &mut s); typeid.push_str(&s); @@ -793,7 +801,12 @@ fn transform_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, options: TransformTyOptio } ty::Array(ty0, len) => { - let len = len.kind().try_to_scalar().unwrap().to_u64().unwrap(); + let len = len + .kind() + .try_to_scalar() + .unwrap() + .to_u64() + .unwrap_or_else(|_| panic!("failed to convert length to u64")); ty = tcx.mk_array(transform_ty(tcx, *ty0, options), len); } diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs index 1ae11f5671cd9..c4abf6f4b5e49 100644 --- a/compiler/rustc_target/src/abi/call/mod.rs +++ b/compiler/rustc_target/src/abi/call/mod.rs @@ -2,7 +2,6 @@ use crate::abi::{self, Abi, Align, FieldsShape, Size}; use crate::abi::{HasDataLayout, TyAbiInterface, TyAndLayout}; use crate::spec::{self, HasTargetSpec}; use rustc_span::Symbol; -use std::fmt; use std::str::FromStr; mod aarch64; @@ -633,16 +632,6 @@ pub enum AdjustForForeignAbiError { Unsupported { arch: Symbol, abi: spec::abi::Abi }, } -impl fmt::Display for AdjustForForeignAbiError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Unsupported { arch, abi } => { - write!(f, "target architecture {arch:?} does not support `extern {abi}` ABI") - } - } - } -} - impl<'a, Ty> FnAbi<'a, Ty> { pub fn adjust_for_foreign_abi( &mut self, diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index c81bf6ebc2eaa..e50474aca746b 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -526,7 +526,7 @@ fn virtual_call_violation_for_method<'tcx>( // #78372 tcx.sess.delay_span_bug( tcx.def_span(method.def_id), - format!("error: {}\n while computing layout for type {:?}", err, ty), + format!("error: {err:?}\n while computing layout for type {ty:?}"), ); None } diff --git a/src/tools/clippy/tests/ui/modulo_one.stderr b/src/tools/clippy/tests/ui/modulo_one.stderr index 04ecdef5e994e..83a76f81d4e78 100644 --- a/src/tools/clippy/tests/ui/modulo_one.stderr +++ b/src/tools/clippy/tests/ui/modulo_one.stderr @@ -2,7 +2,7 @@ error: this operation will panic at runtime --> $DIR/modulo_one.rs:11:5 | LL | i32::MIN % (-1); // also caught by rustc - | ^^^^^^^^^^^^^^^ attempt to compute the remainder of `i32::MIN % -1_i32`, which would overflow + | ^^^^^^^^^^^^^^^ attempt to compute `i32::MIN % -1_i32`, which would overflow | = note: `#[deny(unconditional_panic)]` on by default @@ -10,13 +10,13 @@ error: this operation will panic at runtime --> $DIR/modulo_one.rs:21:5 | LL | INT_MIN % NEG_ONE; // also caught by rustc - | ^^^^^^^^^^^^^^^^^ attempt to compute the remainder of `i64::MIN % -1_i64`, which would overflow + | ^^^^^^^^^^^^^^^^^ attempt to compute `i64::MIN % -1_i64`, which would overflow error: this operation will panic at runtime --> $DIR/modulo_one.rs:22:5 | LL | INT_MIN % STATIC_NEG_ONE; // ONLY caught by rustc - | ^^^^^^^^^^^^^^^^^^^^^^^^ attempt to compute the remainder of `i64::MIN % -1_i64`, which would overflow + | ^^^^^^^^^^^^^^^^^^^^^^^^ attempt to compute `i64::MIN % -1_i64`, which would overflow error: any number modulo 1 will be 0 --> $DIR/modulo_one.rs:8:5 diff --git a/src/tools/miri/src/diagnostics.rs b/src/tools/miri/src/diagnostics.rs index e3f81a78eeaf6..0a89416d02b2c 100644 --- a/src/tools/miri/src/diagnostics.rs +++ b/src/tools/miri/src/diagnostics.rs @@ -3,6 +3,8 @@ use std::num::NonZeroU64; use log::trace; +use rustc_const_eval::const_eval::ReportErrorExt; +use rustc_errors::DiagnosticMessage; use rustc_span::{source_map::DUMMY_SP, SpanData, Symbol}; use rustc_target::abi::{Align, Size}; @@ -83,7 +85,21 @@ impl fmt::Display for TerminationInfo { } } -impl MachineStopType for TerminationInfo {} +impl fmt::Debug for TerminationInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self}") + } +} + +impl MachineStopType for TerminationInfo { + fn diagnostic_message(&self) -> DiagnosticMessage { + self.to_string().into() + } + fn add_args( + self: Box, + _: &mut dyn FnMut(std::borrow::Cow<'static, str>, rustc_errors::DiagnosticArgValue<'static>), + ) {} +} /// Miri specific diagnostics pub enum NonHaltingDiagnostic { @@ -302,8 +318,30 @@ pub fn report_error<'tcx, 'mir>( let stacktrace = ecx.generate_stacktrace(); let (stacktrace, was_pruned) = prune_stacktrace(stacktrace, &ecx.machine); - e.print_backtrace(); - msg.insert(0, e.to_string()); + let (e, backtrace) = e.into_parts(); + backtrace.print_backtrace(); + + let extra = match e { + UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => { + Some((alloc_id, access)) + } + _ => None + }; + + // FIXME(fee1-dead), HACK: we want to use the error as title therefore we can just extract the + // label and arguments from the InterpError. + let e = { + let handler = &ecx.tcx.sess.parse_sess.span_diagnostic; + let mut diag = ecx.tcx.sess.struct_allow(""); + let msg = e.diagnostic_message(); + e.add_args(handler, &mut diag); + let s = handler.eagerly_translate_to_string(msg, diag.args()); + diag.cancel(); + s + }; + + msg.insert(0, e); + report_msg( DiagLevel::Error, &if let Some(title) = title { format!("{title}: {}", msg[0]) } else { msg[0].clone() }, @@ -332,15 +370,12 @@ pub fn report_error<'tcx, 'mir>( } // Extra output to help debug specific issues. - match e.kind() { - UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => { - eprintln!( - "Uninitialized memory occurred at {alloc_id:?}{range:?}, in this allocation:", - range = access.uninit, - ); - eprintln!("{:?}", ecx.dump_alloc(*alloc_id)); - } - _ => {} + if let Some((alloc_id, access)) = extra { + eprintln!( + "Uninitialized memory occurred at {alloc_id:?}{range:?}, in this allocation:", + range = access.uninit, + ); + eprintln!("{:?}", ecx.dump_alloc(alloc_id)); } None @@ -438,12 +473,15 @@ pub fn report_msg<'tcx>( // Add visual separator before backtrace. err.note(if extra_span { "BACKTRACE (of the first span):" } else { "BACKTRACE:" }); } + + let (mut err, handler) = err.into_diagnostic().unwrap(); + // Add backtrace for (idx, frame_info) in stacktrace.iter().enumerate() { let is_local = machine.is_local(frame_info); // No span for non-local frames and the first frame (which is the error site). if is_local && idx > 0 { - err.span_note(frame_info.span, frame_info.to_string()); + err.eager_subdiagnostic(handler, frame_info.as_note(machine.tcx)); } else { let sm = sess.source_map(); let span = sm.span_to_embeddable_string(frame_info.span); @@ -451,7 +489,7 @@ pub fn report_msg<'tcx>( } } - err.emit(); + handler.emit_diagnostic(&mut err); } impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 43d8f221ce3d2..1e9d48be65ed9 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -422,8 +422,9 @@ pub fn eval_entry<'tcx>( let mut ecx = match create_ecx(tcx, entry_id, entry_type, &config) { Ok(v) => v, Err(err) => { - err.print_backtrace(); - panic!("Miri initialization error: {}", err.kind()) + let (kind, backtrace) = err.into_parts(); + backtrace.print_backtrace(); + panic!("Miri initialization error: {kind:?}") } }; diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index a2b49e6f219d3..f11902652393a 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -164,9 +164,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // We don't give a span -- this isn't actually used directly by the program anyway. let const_val = this .eval_global(cid, None) - .unwrap_or_else(|err| panic!("failed to evaluate required Rust item: {path:?}\n{err}")); + .unwrap_or_else(|err| panic!("failed to evaluate required Rust item: {path:?}\n{err:?}")); this.read_scalar(&const_val.into()) - .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err}")) + .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}")) } /// Helper function to get a `libc` constant as a `Scalar`. diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index 893a4dbd4c890..f711f01f3233c 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -43,6 +43,7 @@ extern crate rustc_apfloat; extern crate rustc_ast; +extern crate rustc_errors; #[macro_use] extern crate rustc_middle; extern crate rustc_const_eval; diff --git a/src/tools/miri/tests/fail/intrinsics/copy_overlapping.rs b/src/tools/miri/tests/fail/intrinsics/copy_overlapping.rs index 3df881bd43ca4..9c73bdc17bebc 100644 --- a/src/tools/miri/tests/fail/intrinsics/copy_overlapping.rs +++ b/src/tools/miri/tests/fail/intrinsics/copy_overlapping.rs @@ -10,6 +10,6 @@ fn main() { unsafe { let a = data.as_mut_ptr(); let b = a.wrapping_offset(1) as *mut _; - copy_nonoverlapping(a, b, 2); //~ ERROR: copy_nonoverlapping called on overlapping ranges + copy_nonoverlapping(a, b, 2); //~ ERROR: `copy_nonoverlapping` called on overlapping ranges } } diff --git a/src/tools/miri/tests/fail/intrinsics/copy_overlapping.stderr b/src/tools/miri/tests/fail/intrinsics/copy_overlapping.stderr index cdb3da74ca954..13a76aae73045 100644 --- a/src/tools/miri/tests/fail/intrinsics/copy_overlapping.stderr +++ b/src/tools/miri/tests/fail/intrinsics/copy_overlapping.stderr @@ -1,8 +1,8 @@ -error: Undefined Behavior: copy_nonoverlapping called on overlapping ranges +error: Undefined Behavior: `copy_nonoverlapping` called on overlapping ranges --> $DIR/copy_overlapping.rs:LL:CC | LL | copy_nonoverlapping(a, b, 2); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy_nonoverlapping called on overlapping ranges + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `copy_nonoverlapping` called on overlapping ranges | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.stderr b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.stderr index a31b929d7a7ae..0b9cda62b33c2 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.stderr +++ b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.stderr @@ -1,8 +1,8 @@ -error: Undefined Behavior: out-of-bounds offset_from: ALLOC has size 4, so pointer at offset 10 is out-of-bounds +error: Undefined Behavior: out-of-bounds `offset_from`: ALLOC has size 4, so pointer at offset 10 is out-of-bounds --> $DIR/ptr_offset_from_oob.rs:LL:CC | LL | unsafe { end_ptr.offset_from(end_ptr) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds offset_from: ALLOC has size 4, so pointer at offset 10 is out-of-bounds + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from`: ALLOC has size 4, so pointer at offset 10 is out-of-bounds | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs index 39e34d73f9a43..ffbefce48d3e5 100644 --- a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs @@ -538,7 +538,7 @@ struct LabelWithTrailingPath { #[diag(no_crate_example, code = "E0123")] struct LabelWithTrailingNameValue { #[label(no_crate_label, foo = "...")] - //~^ ERROR invalid nested attribute + //~^ ERROR only `no_span` is a valid nested attribute span: Span, } @@ -546,7 +546,7 @@ struct LabelWithTrailingNameValue { #[diag(no_crate_example, code = "E0123")] struct LabelWithTrailingList { #[label(no_crate_label, foo("..."))] - //~^ ERROR invalid nested attribute + //~^ ERROR only `no_span` is a valid nested attribute span: Span, } diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr index 801e4b5793cc1..1398f9c96bf20 100644 --- a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr @@ -243,7 +243,7 @@ error: invalid nested attribute LL | #[suggestion(nonsense = "bar")] | ^^^^^^^^ | - = help: only `style`, `code` and `applicability` are valid nested attributes + = help: only `no_span`, `style`, `code` and `applicability` are valid nested attributes error: suggestion without `code = "..."` --> $DIR/diagnostic-derive.rs:234:5 @@ -257,7 +257,7 @@ error: invalid nested attribute LL | #[suggestion(msg = "bar")] | ^^^ | - = help: only `style`, `code` and `applicability` are valid nested attributes + = help: only `no_span`, `style`, `code` and `applicability` are valid nested attributes error: suggestion without `code = "..."` --> $DIR/diagnostic-derive.rs:243:5 @@ -335,13 +335,13 @@ error: a diagnostic slug must be the first argument to the attribute LL | #[label(no_crate_label, foo)] | ^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/diagnostic-derive.rs:540:29 | LL | #[label(no_crate_label, foo = "...")] | ^^^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/diagnostic-derive.rs:548:29 | LL | #[label(no_crate_label, foo("..."))] diff --git a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs index 1bfbb60015d59..38af5b0f9fb16 100644 --- a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs +++ b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs @@ -85,7 +85,7 @@ struct F { #[derive(Subdiagnostic)] #[label(bug = "...")] -//~^ ERROR invalid nested attribute +//~^ ERROR only `no_span` is a valid nested attribute //~| ERROR diagnostic slug must be first argument struct G { #[primary_span] @@ -104,7 +104,7 @@ struct H { #[derive(Subdiagnostic)] #[label(slug = 4)] -//~^ ERROR invalid nested attribute +//~^ ERROR only `no_span` is a valid nested attribute //~| ERROR diagnostic slug must be first argument struct J { #[primary_span] @@ -114,7 +114,7 @@ struct J { #[derive(Subdiagnostic)] #[label(slug("..."))] -//~^ ERROR invalid nested attribute +//~^ ERROR only `no_span` is a valid nested attribute //~| ERROR diagnostic slug must be first argument struct K { #[primary_span] @@ -143,7 +143,7 @@ struct M { #[derive(Subdiagnostic)] #[label(no_crate_example, code = "...")] -//~^ ERROR invalid nested attribute +//~^ ERROR only `no_span` is a valid nested attribute struct N { #[primary_span] span: Span, @@ -152,7 +152,7 @@ struct N { #[derive(Subdiagnostic)] #[label(no_crate_example, applicability = "machine-applicable")] -//~^ ERROR invalid nested attribute +//~^ ERROR only `no_span` is a valid nested attribute struct O { #[primary_span] span: Span, @@ -224,7 +224,7 @@ enum T { enum U { #[label(code = "...")] //~^ ERROR diagnostic slug must be first argument of a `#[label(...)]` attribute - //~| ERROR invalid nested attribute + //~| ERROR only `no_span` is a valid nested attribute A { #[primary_span] span: Span, diff --git a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr index fca4f506890bc..5ddc8edd745db 100644 --- a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr +++ b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr @@ -26,7 +26,7 @@ error: `#[label = ...]` is not a valid attribute LL | #[label = "..."] | ^^^^^^^^^^^^^^^^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:87:9 | LL | #[label(bug = "...")] @@ -44,7 +44,7 @@ error: unexpected literal in nested attribute, expected ident LL | #[label("...")] | ^^^^^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:106:9 | LL | #[label(slug = 4)] @@ -56,7 +56,7 @@ error: diagnostic slug must be first argument of a `#[label(...)]` attribute LL | #[label(slug = 4)] | ^^^^^^^^^^^^^^^^^^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:116:9 | LL | #[label(slug("..."))] @@ -74,13 +74,13 @@ error: unexpected end of input, unexpected token in nested attribute, expected i LL | #[label()] | ^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:145:27 | LL | #[label(no_crate_example, code = "...")] | ^^^^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:154:27 | LL | #[label(no_crate_example, applicability = "machine-applicable")] @@ -116,7 +116,7 @@ error: `#[bar(...)]` is not a valid attribute LL | #[bar("...")] | ^^^^^^^^^^^^^ -error: invalid nested attribute +error: only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:225:13 | LL | #[label(code = "...")] @@ -312,7 +312,7 @@ error: invalid nested attribute LL | #[multipart_suggestion(no_crate_example, code = "...", applicability = "machine-applicable")] | ^^^^ | - = help: only `style` and `applicability` are valid nested attributes + = help: only `no_span`, `style` and `applicability` are valid nested attributes error: multipart suggestion without any `#[suggestion_part(...)]` fields --> $DIR/subdiagnostic-derive.rs:540:1 diff --git a/tests/ui/const-generics/generic_const_exprs/issue-80742.stderr b/tests/ui/const-generics/generic_const_exprs/issue-80742.stderr index 6aa8ee13b790f..dc3a400cbaa83 100644 --- a/tests/ui/const-generics/generic_const_exprs/issue-80742.stderr +++ b/tests/ui/const-generics/generic_const_exprs/issue-80742.stderr @@ -1,4 +1,4 @@ -error[E0080]: evaluation of `Inline::::{constant#0}` failed +error[E0080]: evaluation of `Inline::::{constant#0}` failed --> $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: size_of called on unsized type `dyn Debug` @@ -35,7 +35,7 @@ help: consider relaxing the type parameter's implicit `Sized` bound LL | impl Inline | ++++++++ -error[E0080]: evaluation of `Inline::::{constant#0}` failed +error[E0080]: evaluation of `Inline::::{constant#0}` failed --> $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: size_of called on unsized type `dyn Debug` diff --git a/tests/ui/const-ptr/forbidden_slices.stderr b/tests/ui/const-ptr/forbidden_slices.stderr index 817cfb0acf90e..22c3dfa64febc 100644 --- a/tests/ui/const-ptr/forbidden_slices.stderr +++ b/tests/ui/const-ptr/forbidden_slices.stderr @@ -54,11 +54,11 @@ error[E0080]: it is undefined behavior to use this value LL | pub static S5: &[u8] = unsafe { from_raw_parts((&D3) as *const _ as _, size_of::<&u32>()) }; | ^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { HEX_DUMP } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/forbidden_slices.rs:30:1 @@ -98,7 +98,7 @@ LL | from_raw_parts(ptr, 1) error[E0080]: could not evaluate static initializer --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL | - = note: out-of-bounds offset_from: null pointer is a dangling pointer (it has no provenance) + = note: out-of-bounds `offset_from`: null pointer is a dangling pointer (it has no provenance) | note: inside `ptr::const_ptr::::sub_ptr` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL @@ -156,11 +156,11 @@ error[E0080]: it is undefined behavior to use this value LL | pub static R5: &[u8] = unsafe { | ^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { HEX_DUMP } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/forbidden_slices.rs:63:1 diff --git a/tests/ui/consts/const-eval/heap/alloc_intrinsic_errors.stderr b/tests/ui/consts/const-eval/heap/alloc_intrinsic_errors.stderr index 8f3b3d5f700a2..23ba2c2f53516 100644 --- a/tests/ui/consts/const-eval/heap/alloc_intrinsic_errors.stderr +++ b/tests/ui/consts/const-eval/heap/alloc_intrinsic_errors.stderr @@ -2,7 +2,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/alloc_intrinsic_errors.rs:9:17 | LL | let _ = intrinsics::const_allocate(4, 3) as *mut i32; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ align has to be a power of 2, `3` is not a power of 2 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ invalid align passed to `const_allocate`: 3 is not a power of 2 | note: inside `foo` --> $DIR/alloc_intrinsic_errors.rs:9:17 diff --git a/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.rs b/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.rs index f746f27000fff..9ae906bbb7397 100644 --- a/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.rs +++ b/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.rs @@ -4,11 +4,11 @@ use std::intrinsics; const FOO: *const i32 = foo(); -//~^ ERROR untyped pointers are not allowed in constant +//~^ ERROR unsupported untyped pointer in constant const fn foo() -> &'static i32 { let t = unsafe { - let i = intrinsics::const_allocate(4, 4) as * mut i32; + let i = intrinsics::const_allocate(4, 4) as *mut i32; *i = 20; i }; diff --git a/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.stderr b/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.stderr index 00ab0dfc557dd..2103f842bd58e 100644 --- a/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.stderr +++ b/tests/ui/consts/const-eval/heap/alloc_intrinsic_nontransient_fail.stderr @@ -1,8 +1,10 @@ -error: untyped pointers are not allowed in constant +error: unsupported untyped pointer in constant --> $DIR/alloc_intrinsic_nontransient_fail.rs:6:1 | LL | const FOO: *const i32 = foo(); | ^^^^^^^^^^^^^^^^^^^^^ + | + = note: memory only reachable via raw pointers is not supported error: aborting due to previous error diff --git a/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.rs b/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.rs index 77871c394b794..1354b3c33b31d 100644 --- a/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.rs +++ b/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.rs @@ -3,7 +3,7 @@ #![feature(const_mut_refs)] use std::intrinsics; -const BAR: *mut i32 = unsafe { intrinsics::const_allocate(4, 4) as *mut i32}; -//~^ error: untyped pointers are not allowed in constant +const BAR: *mut i32 = unsafe { intrinsics::const_allocate(4, 4) as *mut i32 }; +//~^ error: unsupported untyped pointer in constant fn main() {} diff --git a/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.stderr b/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.stderr index 36002b850b7e7..b6276647350be 100644 --- a/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.stderr +++ b/tests/ui/consts/const-eval/heap/alloc_intrinsic_untyped.stderr @@ -1,8 +1,10 @@ -error: untyped pointers are not allowed in constant +error: unsupported untyped pointer in constant --> $DIR/alloc_intrinsic_untyped.rs:6:1 | -LL | const BAR: *mut i32 = unsafe { intrinsics::const_allocate(4, 4) as *mut i32}; +LL | const BAR: *mut i32 = unsafe { intrinsics::const_allocate(4, 4) as *mut i32 }; | ^^^^^^^^^^^^^^^^^^^ + | + = note: memory only reachable via raw pointers is not supported error: aborting due to previous error diff --git a/tests/ui/consts/const-eval/heap/dealloc_intrinsic_incorrect_layout.stderr b/tests/ui/consts/const-eval/heap/dealloc_intrinsic_incorrect_layout.stderr index 650b409b1908a..4c23957a1f80b 100644 --- a/tests/ui/consts/const-eval/heap/dealloc_intrinsic_incorrect_layout.stderr +++ b/tests/ui/consts/const-eval/heap/dealloc_intrinsic_incorrect_layout.stderr @@ -20,7 +20,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/dealloc_intrinsic_incorrect_layout.rs:25:5 | LL | intrinsics::const_deallocate(ptr, 4, 3); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ align has to be a power of 2, `3` is not a power of 2 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ invalid align passed to `const_deallocate`: 3 is not a power of 2 error: aborting due to 4 previous errors diff --git a/tests/ui/consts/const-eval/raw-bytes.32bit.stderr b/tests/ui/consts/const-eval/raw-bytes.32bit.stderr index a93b561e5be27..c0ddaceea4ce3 100644 --- a/tests/ui/consts/const-eval/raw-bytes.32bit.stderr +++ b/tests/ui/consts/const-eval/raw-bytes.32bit.stderr @@ -35,7 +35,7 @@ error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:44:1 | LL | const BAD_UNINHABITED_VARIANT2: UninhDiscriminant = unsafe { mem::transmute(3u8) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type Never + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type `Never` | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. = note: the raw bytes of the constant (size: 1, align: 1) { @@ -290,11 +290,11 @@ error[E0080]: it is undefined behavior to use this value LL | const MYSTR_NO_INIT_ISSUE83182: &MyStr = unsafe { mem::transmute::<&[_], _>(&[&()]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: 8, align: 4) { ╾ALLOC_ID╼ 01 00 00 00 │ ╾──╼.... } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:152:1 @@ -529,11 +529,11 @@ error[E0080]: it is undefined behavior to use this value LL | pub static S5: &[u8] = unsafe { from_raw_parts((&D3) as *const _ as _, mem::size_of::<&u32>()) }; | ^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: 8, align: 4) { ╾ALLOC_ID╼ 04 00 00 00 │ ╾──╼.... } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:221:1 @@ -574,11 +574,11 @@ error[E0080]: it is undefined behavior to use this value LL | pub static R5: &[u8] = unsafe { | ^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: 8, align: 4) { ╾ALLOC_ID╼ 04 00 00 00 │ ╾──╼.... } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:242:1 diff --git a/tests/ui/consts/const-eval/raw-bytes.64bit.stderr b/tests/ui/consts/const-eval/raw-bytes.64bit.stderr index a32d4863a38f0..20c905878e07c 100644 --- a/tests/ui/consts/const-eval/raw-bytes.64bit.stderr +++ b/tests/ui/consts/const-eval/raw-bytes.64bit.stderr @@ -35,7 +35,7 @@ error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:44:1 | LL | const BAD_UNINHABITED_VARIANT2: UninhDiscriminant = unsafe { mem::transmute(3u8) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type Never + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type `Never` | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. = note: the raw bytes of the constant (size: 1, align: 1) { @@ -290,11 +290,11 @@ error[E0080]: it is undefined behavior to use this value LL | const MYSTR_NO_INIT_ISSUE83182: &MyStr = unsafe { mem::transmute::<&[_], _>(&[&()]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: 16, align: 8) { ╾ALLOC_ID╼ 01 00 00 00 00 00 00 00 │ ╾──────╼........ } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:152:1 @@ -529,11 +529,11 @@ error[E0080]: it is undefined behavior to use this value LL | pub static S5: &[u8] = unsafe { from_raw_parts((&D3) as *const _ as _, mem::size_of::<&u32>()) }; | ^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: 16, align: 8) { ╾ALLOC_ID╼ 08 00 00 00 00 00 00 00 │ ╾──────╼........ } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:221:1 @@ -574,11 +574,11 @@ error[E0080]: it is undefined behavior to use this value LL | pub static R5: &[u8] = unsafe { | ^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: 16, align: 8) { ╾ALLOC_ID╼ 08 00 00 00 00 00 00 00 │ ╾──────╼........ } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: it is undefined behavior to use this value --> $DIR/raw-bytes.rs:242:1 diff --git a/tests/ui/consts/const-eval/ub-enum.32bit.stderr b/tests/ui/consts/const-eval/ub-enum.32bit.stderr index 3ad1ac974c806..1810600b78514 100644 --- a/tests/ui/consts/const-eval/ub-enum.32bit.stderr +++ b/tests/ui/consts/const-eval/ub-enum.32bit.stderr @@ -86,7 +86,7 @@ error[E0080]: it is undefined behavior to use this value --> $DIR/ub-enum.rs:83:1 | LL | const BAD_UNINHABITED_VARIANT2: UninhDiscriminant = unsafe { mem::transmute(3u8) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type Never + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type `Never` | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { @@ -108,7 +108,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/ub-enum.rs:96:77 | LL | const BAD_UNINHABITED_WITH_DATA1: Result<(i32, Never), (i32, !)> = unsafe { mem::transmute(0u64) }; - | ^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0.1: encountered a value of uninhabited type Never + | ^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0.1: encountered a value of uninhabited type `Never` error[E0080]: evaluation of constant value failed --> $DIR/ub-enum.rs:98:77 diff --git a/tests/ui/consts/const-eval/ub-enum.64bit.stderr b/tests/ui/consts/const-eval/ub-enum.64bit.stderr index a66706d1af9b8..fb40babb0b9c3 100644 --- a/tests/ui/consts/const-eval/ub-enum.64bit.stderr +++ b/tests/ui/consts/const-eval/ub-enum.64bit.stderr @@ -86,7 +86,7 @@ error[E0080]: it is undefined behavior to use this value --> $DIR/ub-enum.rs:83:1 | LL | const BAD_UNINHABITED_VARIANT2: UninhDiscriminant = unsafe { mem::transmute(3u8) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type Never + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0: encountered a value of uninhabited type `Never` | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { @@ -108,7 +108,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/ub-enum.rs:96:77 | LL | const BAD_UNINHABITED_WITH_DATA1: Result<(i32, Never), (i32, !)> = unsafe { mem::transmute(0u64) }; - | ^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0.1: encountered a value of uninhabited type Never + | ^^^^^^^^^^^^^^^^^^^^ constructing invalid value at ..0.1: encountered a value of uninhabited type `Never` error[E0080]: evaluation of constant value failed --> $DIR/ub-enum.rs:98:77 diff --git a/tests/ui/consts/const-eval/ub-uninhabit.stderr b/tests/ui/consts/const-eval/ub-uninhabit.stderr index 733975fc0e9ce..f1ad0f04d3dbe 100644 --- a/tests/ui/consts/const-eval/ub-uninhabit.stderr +++ b/tests/ui/consts/const-eval/ub-uninhabit.stderr @@ -2,7 +2,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/ub-uninhabit.rs:16:35 | LL | const BAD_BAD_BAD: Bar = unsafe { MaybeUninit { uninit: () }.init }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a value of uninhabited type Bar + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a value of uninhabited type `Bar` error[E0080]: it is undefined behavior to use this value --> $DIR/ub-uninhabit.rs:19:1 @@ -19,7 +19,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/ub-uninhabit.rs:22:42 | LL | const BAD_BAD_ARRAY: [Bar; 1] = unsafe { MaybeUninit { uninit: () }.init }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at [0]: encountered a value of uninhabited type Bar + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at [0]: encountered a value of uninhabited type `Bar` error: aborting due to 3 previous errors diff --git a/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr b/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr index 74bc6317c808e..b423edbdcec8d 100644 --- a/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr +++ b/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr @@ -28,7 +28,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/validate_uninhabited_zsts.rs:21:42 | LL | const BAR: [empty::Empty; 3] = [unsafe { std::mem::transmute(()) }; 3]; - | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .0: encountered a value of uninhabited type empty::Void + | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .0: encountered a value of uninhabited type `Void` warning: the type `empty::Empty` does not permit zero-initialization --> $DIR/validate_uninhabited_zsts.rs:21:42 diff --git a/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr b/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr index 74bc6317c808e..b423edbdcec8d 100644 --- a/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr +++ b/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr @@ -28,7 +28,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/validate_uninhabited_zsts.rs:21:42 | LL | const BAR: [empty::Empty; 3] = [unsafe { std::mem::transmute(()) }; 3]; - | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .0: encountered a value of uninhabited type empty::Void + | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .0: encountered a value of uninhabited type `Void` warning: the type `empty::Empty` does not permit zero-initialization --> $DIR/validate_uninhabited_zsts.rs:21:42 diff --git a/tests/ui/consts/issue-64506.stderr b/tests/ui/consts/issue-64506.stderr index 31a5b1df837c5..2fe84245b3ef8 100644 --- a/tests/ui/consts/issue-64506.stderr +++ b/tests/ui/consts/issue-64506.stderr @@ -2,7 +2,7 @@ error[E0080]: evaluation of constant value failed --> $DIR/issue-64506.rs:16:22 | LL | let x = unsafe { Foo { b: () }.a }; - | ^^^^^^^^^^^^^^^ constructing invalid value at .inner: encountered a value of uninhabited type AnonPipe + | ^^^^^^^^^^^^^^^ constructing invalid value at .inner: encountered a value of uninhabited type `AnonPipe` error: aborting due to previous error diff --git a/tests/ui/consts/issue-83182.stderr b/tests/ui/consts/issue-83182.stderr index 1d578f910c040..ca4e0f7aa0239 100644 --- a/tests/ui/consts/issue-83182.stderr +++ b/tests/ui/consts/issue-83182.stderr @@ -4,11 +4,11 @@ error[E0080]: it is undefined behavior to use this value LL | const MYSTR_NO_INIT: &MyStr = unsafe { mem::transmute::<&[_], _>(&[&()]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { HEX_DUMP } + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error: aborting due to previous error diff --git a/tests/ui/consts/issue-miri-1910.stderr b/tests/ui/consts/issue-miri-1910.stderr index fb758d406b550..67797e6fb5a85 100644 --- a/tests/ui/consts/issue-miri-1910.stderr +++ b/tests/ui/consts/issue-miri-1910.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | = note: unable to turn pointer into raw bytes | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported note: inside `std::ptr::read::` --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL note: inside `ptr::const_ptr::::read` @@ -14,6 +12,8 @@ note: inside `C` | LL | (&foo as *const _ as *const u8).add(one_and_a_half_pointers).read(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error: aborting due to previous error diff --git a/tests/ui/consts/miri_unleashed/assoc_const.stderr b/tests/ui/consts/miri_unleashed/assoc_const.stderr index 8e22cb74bf56a..d97097d352a64 100644 --- a/tests/ui/consts/miri_unleashed/assoc_const.stderr +++ b/tests/ui/consts/miri_unleashed/assoc_const.stderr @@ -1,4 +1,4 @@ -error[E0080]: evaluation of `, std::string::String>>::F` failed +error[E0080]: evaluation of `, String>>::F` failed --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL | = note: calling non-const function ` as Drop>::drop` diff --git a/tests/ui/consts/miri_unleashed/raw_mutable_const.rs b/tests/ui/consts/miri_unleashed/raw_mutable_const.rs index 5f8ec4e6e294d..adb1f8bf3ec55 100644 --- a/tests/ui/consts/miri_unleashed/raw_mutable_const.rs +++ b/tests/ui/consts/miri_unleashed/raw_mutable_const.rs @@ -3,6 +3,6 @@ use std::cell::UnsafeCell; const MUTABLE_BEHIND_RAW: *mut i32 = &UnsafeCell::new(42) as *const _ as *mut _; -//~^ ERROR: untyped pointers are not allowed in constant +//~^ ERROR: unsupported untyped pointer in constant fn main() {} diff --git a/tests/ui/consts/miri_unleashed/raw_mutable_const.stderr b/tests/ui/consts/miri_unleashed/raw_mutable_const.stderr index f8dc11d695f11..5acdcdd95e8e3 100644 --- a/tests/ui/consts/miri_unleashed/raw_mutable_const.stderr +++ b/tests/ui/consts/miri_unleashed/raw_mutable_const.stderr @@ -1,8 +1,10 @@ -error: untyped pointers are not allowed in constant +error: unsupported untyped pointer in constant --> $DIR/raw_mutable_const.rs:5:1 | LL | const MUTABLE_BEHIND_RAW: *mut i32 = &UnsafeCell::new(42) as *const _ as *mut _; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: memory only reachable via raw pointers is not supported warning: skipping const checks | diff --git a/tests/ui/consts/missing_span_in_backtrace.stderr b/tests/ui/consts/missing_span_in_backtrace.stderr index e6d3d51990dd5..fcfb9fbb3f8c0 100644 --- a/tests/ui/consts/missing_span_in_backtrace.stderr +++ b/tests/ui/consts/missing_span_in_backtrace.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | = note: unable to copy parts of a pointer from memory at ALLOC_ID | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported note: inside `std::ptr::read::>>` --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL note: inside `mem::swap_simple::>>` @@ -22,6 +20,8 @@ note: inside `X` 20 | | mem::size_of::<&i32>(), 21 | | ); | |_________^ + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error: aborting due to previous error diff --git a/tests/ui/consts/offset_from_ub.stderr b/tests/ui/consts/offset_from_ub.stderr index 6530084a5857d..97ff6efdd791c 100644 --- a/tests/ui/consts/offset_from_ub.stderr +++ b/tests/ui/consts/offset_from_ub.stderr @@ -27,31 +27,31 @@ error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:37:14 | LL | unsafe { ptr_offset_from(ptr, ptr) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds offset_from: null pointer is a dangling pointer (it has no provenance) + | ^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from`: null pointer is a dangling pointer (it has no provenance) error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:44:14 | LL | unsafe { ptr_offset_from(ptr2, ptr1) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds offset_from: 0x8[noalloc] is a dangling pointer (it has no provenance) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from`: 0x8[noalloc] is a dangling pointer (it has no provenance) error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:53:14 | LL | unsafe { ptr_offset_from(end_ptr, start_ptr) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds offset_from: alloc17 has size 4, so pointer to 10 bytes starting at offset 0 is out-of-bounds + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from`: alloc17 has size 4, so pointer to 10 bytes starting at offset 0 is out-of-bounds error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:62:14 | LL | unsafe { ptr_offset_from(start_ptr, end_ptr) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds offset_from: alloc20 has size 4, so pointer to 10 bytes starting at offset 0 is out-of-bounds + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from`: alloc20 has size 4, so pointer to 10 bytes starting at offset 0 is out-of-bounds error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:70:14 | LL | unsafe { ptr_offset_from(end_ptr, end_ptr) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds offset_from: alloc23 has size 4, so pointer at offset 10 is out-of-bounds + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from`: alloc23 has size 4, so pointer at offset 10 is out-of-bounds error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:79:14 @@ -86,7 +86,7 @@ LL | unsafe { ptr_offset_from_unsigned(ptr2, ptr1) } error[E0080]: evaluation of constant value failed --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL | - = note: out-of-bounds offset_from: null pointer is a dangling pointer (it has no provenance) + = note: out-of-bounds `offset_from`: null pointer is a dangling pointer (it has no provenance) | note: inside `ptr::const_ptr::::offset_from` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL @@ -99,7 +99,7 @@ LL | unsafe { ptr2.offset_from(ptr1) } error[E0080]: evaluation of constant value failed --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL | - = note: out-of-bounds offset_from: null pointer is a dangling pointer (it has no provenance) + = note: out-of-bounds `offset_from`: null pointer is a dangling pointer (it has no provenance) | note: inside `ptr::const_ptr::::offset_from` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL diff --git a/tests/ui/consts/raw-ptr-const.rs b/tests/ui/consts/raw-ptr-const.rs index b9c542d03d5a9..fc774be54dff3 100644 --- a/tests/ui/consts/raw-ptr-const.rs +++ b/tests/ui/consts/raw-ptr-const.rs @@ -3,6 +3,6 @@ // could also be allowed. const CONST_RAW: *const Vec = &Vec::new() as *const _; -//~^ ERROR untyped pointers are not allowed in constant +//~^ ERROR unsupported untyped pointer in constant fn main() {} diff --git a/tests/ui/consts/raw-ptr-const.stderr b/tests/ui/consts/raw-ptr-const.stderr index f7b53433b6994..82f782fab7f54 100644 --- a/tests/ui/consts/raw-ptr-const.stderr +++ b/tests/ui/consts/raw-ptr-const.stderr @@ -1,8 +1,10 @@ -error: untyped pointers are not allowed in constant +error: unsupported untyped pointer in constant --> $DIR/raw-ptr-const.rs:5:1 | LL | const CONST_RAW: *const Vec = &Vec::new() as *const _; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: memory only reachable via raw pointers is not supported error: aborting due to previous error diff --git a/tests/ui/numbers-arithmetic/issue-8460-const.noopt.stderr b/tests/ui/numbers-arithmetic/issue-8460-const.noopt.stderr index c4abcb784119e..2fba94d07401c 100644 --- a/tests/ui/numbers-arithmetic/issue-8460-const.noopt.stderr +++ b/tests/ui/numbers-arithmetic/issue-8460-const.noopt.stderr @@ -76,37 +76,37 @@ error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:35:36 | LL | assert!(thread::spawn(move|| { isize::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^^^ attempt to compute the remainder of `isize::MIN % -1_isize`, which would overflow + | ^^^^^^^^^^^^^^^ attempt to compute `isize::MIN % -1_isize`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:37:36 | LL | assert!(thread::spawn(move|| { i8::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^ attempt to compute the remainder of `i8::MIN % -1_i8`, which would overflow + | ^^^^^^^^^^^^ attempt to compute `i8::MIN % -1_i8`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:39:36 | LL | assert!(thread::spawn(move|| { i16::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i16::MIN % -1_i16`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i16::MIN % -1_i16`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:41:36 | LL | assert!(thread::spawn(move|| { i32::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i32::MIN % -1_i32`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i32::MIN % -1_i32`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:43:36 | LL | assert!(thread::spawn(move|| { i64::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i64::MIN % -1_i64`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i64::MIN % -1_i64`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:45:36 | LL | assert!(thread::spawn(move|| { i128::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^^ attempt to compute the remainder of `i128::MIN % -1_i128`, which would overflow + | ^^^^^^^^^^^^^^ attempt to compute `i128::MIN % -1_i128`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:47:36 diff --git a/tests/ui/numbers-arithmetic/issue-8460-const.opt.stderr b/tests/ui/numbers-arithmetic/issue-8460-const.opt.stderr index c4abcb784119e..2fba94d07401c 100644 --- a/tests/ui/numbers-arithmetic/issue-8460-const.opt.stderr +++ b/tests/ui/numbers-arithmetic/issue-8460-const.opt.stderr @@ -76,37 +76,37 @@ error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:35:36 | LL | assert!(thread::spawn(move|| { isize::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^^^ attempt to compute the remainder of `isize::MIN % -1_isize`, which would overflow + | ^^^^^^^^^^^^^^^ attempt to compute `isize::MIN % -1_isize`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:37:36 | LL | assert!(thread::spawn(move|| { i8::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^ attempt to compute the remainder of `i8::MIN % -1_i8`, which would overflow + | ^^^^^^^^^^^^ attempt to compute `i8::MIN % -1_i8`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:39:36 | LL | assert!(thread::spawn(move|| { i16::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i16::MIN % -1_i16`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i16::MIN % -1_i16`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:41:36 | LL | assert!(thread::spawn(move|| { i32::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i32::MIN % -1_i32`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i32::MIN % -1_i32`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:43:36 | LL | assert!(thread::spawn(move|| { i64::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i64::MIN % -1_i64`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i64::MIN % -1_i64`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:45:36 | LL | assert!(thread::spawn(move|| { i128::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^^ attempt to compute the remainder of `i128::MIN % -1_i128`, which would overflow + | ^^^^^^^^^^^^^^ attempt to compute `i128::MIN % -1_i128`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:47:36 diff --git a/tests/ui/numbers-arithmetic/issue-8460-const.opt_with_overflow_checks.stderr b/tests/ui/numbers-arithmetic/issue-8460-const.opt_with_overflow_checks.stderr index c4abcb784119e..2fba94d07401c 100644 --- a/tests/ui/numbers-arithmetic/issue-8460-const.opt_with_overflow_checks.stderr +++ b/tests/ui/numbers-arithmetic/issue-8460-const.opt_with_overflow_checks.stderr @@ -76,37 +76,37 @@ error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:35:36 | LL | assert!(thread::spawn(move|| { isize::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^^^ attempt to compute the remainder of `isize::MIN % -1_isize`, which would overflow + | ^^^^^^^^^^^^^^^ attempt to compute `isize::MIN % -1_isize`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:37:36 | LL | assert!(thread::spawn(move|| { i8::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^ attempt to compute the remainder of `i8::MIN % -1_i8`, which would overflow + | ^^^^^^^^^^^^ attempt to compute `i8::MIN % -1_i8`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:39:36 | LL | assert!(thread::spawn(move|| { i16::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i16::MIN % -1_i16`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i16::MIN % -1_i16`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:41:36 | LL | assert!(thread::spawn(move|| { i32::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i32::MIN % -1_i32`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i32::MIN % -1_i32`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:43:36 | LL | assert!(thread::spawn(move|| { i64::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^ attempt to compute the remainder of `i64::MIN % -1_i64`, which would overflow + | ^^^^^^^^^^^^^ attempt to compute `i64::MIN % -1_i64`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:45:36 | LL | assert!(thread::spawn(move|| { i128::MIN % -1; }).join().is_err()); - | ^^^^^^^^^^^^^^ attempt to compute the remainder of `i128::MIN % -1_i128`, which would overflow + | ^^^^^^^^^^^^^^ attempt to compute `i128::MIN % -1_i128`, which would overflow error: this operation will panic at runtime --> $DIR/issue-8460-const.rs:47:36 diff --git a/tests/ui/statics/uninhabited-static.stderr b/tests/ui/statics/uninhabited-static.stderr index 35fdcae6a598a..9260930473fa8 100644 --- a/tests/ui/statics/uninhabited-static.stderr +++ b/tests/ui/statics/uninhabited-static.stderr @@ -47,7 +47,7 @@ error[E0080]: could not evaluate static initializer --> $DIR/uninhabited-static.rs:12:31 | LL | static VOID2: Void = unsafe { std::mem::transmute(()) }; - | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a value of uninhabited type Void + | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a value of uninhabited type `Void` warning: the type `Void` does not permit zero-initialization --> $DIR/uninhabited-static.rs:12:31 @@ -66,7 +66,7 @@ error[E0080]: could not evaluate static initializer --> $DIR/uninhabited-static.rs:16:32 | LL | static NEVER2: Void = unsafe { std::mem::transmute(()) }; - | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a value of uninhabited type Void + | ^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a value of uninhabited type `Void` warning: the type `Void` does not permit zero-initialization --> $DIR/uninhabited-static.rs:16:32 From 91525a43243e088abb34fca3d43fd8588b8667e0 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 24 May 2023 17:11:40 +0000 Subject: [PATCH 11/15] Use ErrorGuaranteed more in MIR type ops --- .../src/type_check/canonical.rs | 45 +++++----------- .../src/type_check/free_region_relations.rs | 21 +++----- .../src/type_check/liveness/trace.rs | 16 ++++-- compiler/rustc_borrowck/src/type_check/mod.rs | 54 +++++++++++-------- .../src/type_check/relate_tys.rs | 15 ++---- .../src/traits/outlives_bounds.rs | 12 ++--- .../src/traits/query/type_op/custom.rs | 24 ++++++--- .../src/traits/query/type_op/mod.rs | 24 +++++++-- 8 files changed, 104 insertions(+), 107 deletions(-) diff --git a/compiler/rustc_borrowck/src/type_check/canonical.rs b/compiler/rustc_borrowck/src/type_check/canonical.rs index 95dcc8d4b1916..f527eee7bda05 100644 --- a/compiler/rustc_borrowck/src/type_check/canonical.rs +++ b/compiler/rustc_borrowck/src/type_check/canonical.rs @@ -1,12 +1,12 @@ use std::fmt; +use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::canonical::Canonical; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable}; use rustc_span::def_id::DefId; use rustc_span::Span; use rustc_trait_selection::traits::query::type_op::{self, TypeOpOutput}; -use rustc_trait_selection::traits::query::{Fallible, NoSolution}; use rustc_trait_selection::traits::ObligationCause; use crate::diagnostics::{ToUniverseInfo, UniverseInfo}; @@ -30,14 +30,15 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { locations: Locations, category: ConstraintCategory<'tcx>, op: Op, - ) -> Fallible + ) -> Result where Op: type_op::TypeOp<'tcx, Output = R>, Op::ErrorInfo: ToUniverseInfo<'tcx>, { let old_universe = self.infcx.universe(); - let TypeOpOutput { output, constraints, error_info } = op.fully_perform(self.infcx)?; + let TypeOpOutput { output, constraints, error_info } = + op.fully_perform(self.infcx, locations.span(self.body))?; debug!(?output, ?constraints); @@ -135,14 +136,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { ) { let param_env = self.param_env; let predicate = predicate.to_predicate(self.tcx()); - self.fully_perform_op( + let _: Result<_, ErrorGuaranteed> = self.fully_perform_op( locations, category, param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)), - ) - .unwrap_or_else(|NoSolution| { - span_mirbug!(self, NoSolution, "could not prove {:?}", predicate); - }) + ); } pub(super) fn normalize(&mut self, value: T, location: impl NormalizeLocation) -> T @@ -163,15 +161,12 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { T: type_op::normalize::Normalizable<'tcx> + fmt::Display + Copy + 'tcx, { let param_env = self.param_env; - self.fully_perform_op( + let result: Result<_, ErrorGuaranteed> = self.fully_perform_op( location.to_locations(), category, param_env.and(type_op::normalize::Normalize::new(value)), - ) - .unwrap_or_else(|NoSolution| { - span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value); - value - }) + ); + result.unwrap_or(value) } #[instrument(skip(self), level = "debug")] @@ -181,18 +176,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { user_ty: ty::UserType<'tcx>, span: Span, ) { - self.fully_perform_op( + let _: Result<_, ErrorGuaranteed> = self.fully_perform_op( Locations::All(span), ConstraintCategory::Boring, self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(mir_ty, user_ty)), - ) - .unwrap_or_else(|err| { - span_mirbug!( - self, - span, - "ascribe_user_type `{mir_ty:?}=={user_ty:?}` failed with `{err:?}`", - ); - }); + ); } /// *Incorrectly* skips the WF checks we normally do in `ascribe_user_type`. @@ -219,7 +207,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let cause = ObligationCause::dummy_with_span(span); let param_env = self.param_env; - self.fully_perform_op( + let _: Result<_, ErrorGuaranteed> = self.fully_perform_op( Locations::All(span), ConstraintCategory::Boring, type_op::custom::CustomTypeOp::new( @@ -230,13 +218,6 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { }, "ascribe_user_type_skip_wf", ), - ) - .unwrap_or_else(|err| { - span_mirbug!( - self, - span, - "ascribe_user_type_skip_wf `{mir_ty:?}=={user_ty:?}` failed with `{err:?}`", - ); - }); + ); } } diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs index bd01c0b504cb5..c8ec1257d376e 100644 --- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs +++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs @@ -8,7 +8,7 @@ use rustc_infer::infer::InferCtxt; use rustc_middle::mir::ConstraintCategory; use rustc_middle::traits::query::OutlivesBound; use rustc_middle::ty::{self, RegionVid, Ty}; -use rustc_span::Span; +use rustc_span::{Span, DUMMY_SP}; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; use std::rc::Rc; use type_op::TypeOpOutput; @@ -243,18 +243,11 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> { let TypeOpOutput { output: norm_ty, constraints: constraints_normalize, .. } = self .param_env .and(type_op::normalize::Normalize::new(ty)) - .fully_perform(self.infcx) - .unwrap_or_else(|_| { - let guar = self - .infcx - .tcx - .sess - .delay_span_bug(span, format!("failed to normalize {:?}", ty)); - TypeOpOutput { - output: self.infcx.tcx.ty_error(guar), - constraints: None, - error_info: None, - } + .fully_perform(self.infcx, span) + .unwrap_or_else(|guar| TypeOpOutput { + output: self.infcx.tcx.ty_error(guar), + constraints: None, + error_info: None, }); if let Some(c) = constraints_normalize { constraints.push(c) @@ -324,7 +317,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> { let TypeOpOutput { output: bounds, constraints, .. } = self .param_env .and(type_op::implied_outlives_bounds::ImpliedOutlivesBounds { ty }) - .fully_perform(self.infcx) + .fully_perform(self.infcx, DUMMY_SP) .unwrap_or_else(|_| bug!("failed to compute implied bounds {:?}", ty)); debug!(?bounds, ?constraints); self.add_outlives_bounds(bounds); diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs index 9731b10aa99d9..fd94ac86d7dc2 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs @@ -4,6 +4,7 @@ use rustc_index::interval::IntervalSet; use rustc_infer::infer::canonical::QueryRegionConstraints; use rustc_middle::mir::{BasicBlock, Body, ConstraintCategory, Local, Location}; use rustc_middle::ty::{Ty, TyCtxt, TypeVisitable, TypeVisitableExt}; +use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::dropck_outlives::DropckOutlivesResult; use rustc_trait_selection::traits::query::type_op::outlives::DropckOutlives; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; @@ -568,10 +569,15 @@ impl<'tcx> LivenessContext<'_, '_, '_, 'tcx> { ) -> DropData<'tcx> { debug!("compute_drop_data(dropped_ty={:?})", dropped_ty,); - let param_env = typeck.param_env; - let TypeOpOutput { output, constraints, .. } = - param_env.and(DropckOutlives::new(dropped_ty)).fully_perform(typeck.infcx).unwrap(); - - DropData { dropck_result: output, region_constraint_data: constraints } + match typeck + .param_env + .and(DropckOutlives::new(dropped_ty)) + .fully_perform(typeck.infcx, DUMMY_SP) + { + Ok(TypeOpOutput { output, constraints, .. }) => { + DropData { dropck_result: output, region_constraint_data: constraints } + } + Err(_) => DropData { dropck_result: Default::default(), region_constraint_data: None }, + } } } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index cf204cff6b3a7..b2693e6054674 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -10,6 +10,7 @@ use either::Either; use hir::OpaqueTyOrigin; use rustc_data_structures::frozen::Frozen; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; +use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; @@ -216,24 +217,22 @@ pub(crate) fn type_check<'mir, 'tcx>( let opaque_type_values = opaque_type_values .into_iter() .map(|(opaque_type_key, decl)| { - checker - .fully_perform_op( - Locations::All(body.span), - ConstraintCategory::OpaqueType, - CustomTypeOp::new( - |ocx| { - ocx.infcx.register_member_constraints( - param_env, - opaque_type_key, - decl.hidden_type.ty, - decl.hidden_type.span, - ); - Ok(()) - }, - "opaque_type_map", - ), - ) - .unwrap(); + let _: Result<_, ErrorGuaranteed> = checker.fully_perform_op( + Locations::All(body.span), + ConstraintCategory::OpaqueType, + CustomTypeOp::new( + |ocx| { + ocx.infcx.register_member_constraints( + param_env, + opaque_type_key, + decl.hidden_type.ty, + decl.hidden_type.span, + ); + Ok(()) + }, + "opaque_type_map", + ), + ); let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type); trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind()); if hidden_type.has_non_region_infer() { @@ -2755,11 +2754,20 @@ impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> { /// constraints in our `InferCtxt` type ErrorInfo = InstantiateOpaqueType<'tcx>; - fn fully_perform(mut self, infcx: &InferCtxt<'tcx>) -> Fallible> { - let (mut output, region_constraints) = scrape_region_constraints(infcx, |ocx| { - ocx.register_obligations(self.obligations.clone()); - Ok(()) - })?; + fn fully_perform( + mut self, + infcx: &InferCtxt<'tcx>, + span: Span, + ) -> Result, ErrorGuaranteed> { + let (mut output, region_constraints) = scrape_region_constraints( + infcx, + |ocx| { + ocx.register_obligations(self.obligations.clone()); + Ok(()) + }, + "InstantiateOpaqueType", + span, + )?; self.region_constraints = Some(region_constraints); output.error_info = Some(self); Ok(output) diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index dd1f89e5b9157..6f3451d56574e 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -1,3 +1,4 @@ +use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::nll_relate::{TypeRelating, TypeRelatingDelegate}; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_infer::traits::PredicateObligations; @@ -185,7 +186,7 @@ impl<'tcx> TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, 'tcx> } fn register_obligations(&mut self, obligations: PredicateObligations<'tcx>) { - match self.type_checker.fully_perform_op( + let _: Result<_, ErrorGuaranteed> = self.type_checker.fully_perform_op( self.locations, self.category, InstantiateOpaqueType { @@ -194,16 +195,6 @@ impl<'tcx> TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, 'tcx> base_universe: None, region_constraints: None, }, - ) { - Ok(()) => {} - Err(_) => { - // It's a bit redundant to delay a bug here, but I'd rather - // delay more bugs than accidentally not delay a bug at all. - self.type_checker.tcx().sess.delay_span_bug( - self.locations.span(self.type_checker.body), - "errors selecting obligation during MIR typeck", - ); - } - }; + ); } } diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index 0db8023289127..0e797a1cb60d5 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -1,8 +1,8 @@ use crate::infer::InferCtxt; use crate::traits::query::type_op::{self, TypeOp, TypeOpOutput}; -use crate::traits::query::NoSolution; use crate::traits::{ObligationCause, ObligationCtxt}; use rustc_data_structures::fx::FxIndexSet; +use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_middle::ty::{self, ParamEnv, Ty, TypeFolder, TypeVisitableExt}; use rustc_span::def_id::LocalDefId; @@ -69,16 +69,12 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { } let span = self.tcx.def_span(body_id); - let result = param_env + let result: Result<_, ErrorGuaranteed> = param_env .and(type_op::implied_outlives_bounds::ImpliedOutlivesBounds { ty }) - .fully_perform(self); + .fully_perform(self, span); let result = match result { Ok(r) => r, - Err(NoSolution) => { - self.tcx.sess.delay_span_bug( - span, - "implied_outlives_bounds failed to solve all obligations", - ); + Err(_) => { return vec![]; } }; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs index 3d6c1d9e2b02e..94464895f3b2e 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs @@ -3,9 +3,10 @@ use crate::infer::InferCtxt; use crate::traits::query::type_op::TypeOpOutput; use crate::traits::query::Fallible; use crate::traits::ObligationCtxt; +use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::region_constraints::RegionConstraintData; -use rustc_middle::traits::query::NoSolution; use rustc_span::source_map::DUMMY_SP; +use rustc_span::Span; use std::fmt; @@ -35,12 +36,16 @@ where /// Processes the operation and all resulting obligations, /// returning the final result along with any region constraints /// (they will be given over to the NLL region solver). - fn fully_perform(self, infcx: &InferCtxt<'tcx>) -> Fallible> { + fn fully_perform( + self, + infcx: &InferCtxt<'tcx>, + span: Span, + ) -> Result, ErrorGuaranteed> { if cfg!(debug_assertions) { info!("fully_perform({:?})", self); } - Ok(scrape_region_constraints(infcx, self.closure)?.0) + Ok(scrape_region_constraints(infcx, self.closure, self.description, span)?.0) } } @@ -55,7 +60,9 @@ impl fmt::Debug for CustomTypeOp { pub fn scrape_region_constraints<'tcx, Op: super::TypeOp<'tcx, Output = R>, R>( infcx: &InferCtxt<'tcx>, op: impl FnOnce(&ObligationCtxt<'_, 'tcx>) -> Fallible, -) -> Fallible<(TypeOpOutput<'tcx, Op>, RegionConstraintData<'tcx>)> { + name: &'static str, + span: Span, +) -> Result<(TypeOpOutput<'tcx, Op>, RegionConstraintData<'tcx>), ErrorGuaranteed> { // During NLL, we expect that nobody will register region // obligations **except** as part of a custom type op (and, at the // end of each custom type op, we scrape out the region @@ -70,16 +77,17 @@ pub fn scrape_region_constraints<'tcx, Op: super::TypeOp<'tcx, Output = R>, R>( let value = infcx.commit_if_ok(|_| { let ocx = ObligationCtxt::new_in_snapshot(infcx); - let value = op(&ocx)?; + let value = op(&ocx).map_err(|_| { + infcx.tcx.sess.delay_span_bug(span, format!("error performing operation: {name}")) + })?; let errors = ocx.select_all_or_error(); if errors.is_empty() { Ok(value) } else { - infcx.tcx.sess.delay_span_bug( + Err(infcx.tcx.sess.delay_span_bug( DUMMY_SP, format!("errors selecting obligation during MIR typeck: {:?}", errors), - ); - Err(NoSolution) + )) } })?; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs index 9e8bc8bce9a8f..a34ea3fb3dd30 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs @@ -4,11 +4,12 @@ use crate::infer::canonical::{ use crate::infer::{InferCtxt, InferOk}; use crate::traits::query::Fallible; use crate::traits::ObligationCause; +use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::canonical::Certainty; -use rustc_infer::traits::query::NoSolution; use rustc_infer::traits::PredicateObligations; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; +use rustc_span::Span; use std::fmt; pub mod ascribe_user_type; @@ -32,7 +33,11 @@ pub trait TypeOp<'tcx>: Sized + fmt::Debug { /// Processes the operation and all resulting obligations, /// returning the final result along with any region constraints /// (they will be given over to the NLL region solver). - fn fully_perform(self, infcx: &InferCtxt<'tcx>) -> Fallible>; + fn fully_perform( + self, + infcx: &InferCtxt<'tcx>, + span: Span, + ) -> Result, ErrorGuaranteed>; } /// The output from performing a type op @@ -120,10 +125,16 @@ where type Output = Q::QueryResponse; type ErrorInfo = Canonical<'tcx, ParamEnvAnd<'tcx, Q>>; - fn fully_perform(self, infcx: &InferCtxt<'tcx>) -> Fallible> { + fn fully_perform( + self, + infcx: &InferCtxt<'tcx>, + span: Span, + ) -> Result, ErrorGuaranteed> { let mut region_constraints = QueryRegionConstraints::default(); let (output, error_info, mut obligations, _) = - Q::fully_perform_into(self, infcx, &mut region_constraints)?; + Q::fully_perform_into(self, infcx, &mut region_constraints).map_err(|_| { + infcx.tcx.sess.delay_span_bug(span, format!("error performing {self:?}")) + })?; // Typically, instantiating NLL query results does not // create obligations. However, in some cases there @@ -151,7 +162,10 @@ where } } if !progress { - return Err(NoSolution); + return Err(infcx.tcx.sess.delay_span_bug( + span, + format!("ambiguity processing {obligations:?} from {self:?}"), + )); } } From 0a35db5e0d0f855ec9706280cef21fdc8a1f6ce5 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 25 May 2023 17:29:22 +0000 Subject: [PATCH 12/15] Fallible<_> -> Result<_, NoSolution> --- compiler/rustc_borrowck/src/type_check/mod.rs | 9 +++++---- .../src/type_check/relate_tys.rs | 6 +++--- .../src/infer/canonical/query_response.rs | 4 ++-- compiler/rustc_middle/src/traits/query.rs | 2 -- compiler/rustc_trait_selection/src/infer.rs | 10 +++++----- .../src/traits/engine.rs | 4 ++-- .../traits/query/type_op/ascribe_user_type.rs | 4 ++-- .../src/traits/query/type_op/custom.rs | 8 ++++---- .../src/traits/query/type_op/eq.rs | 4 ++-- .../query/type_op/implied_outlives_bounds.rs | 4 ++-- .../src/traits/query/type_op/mod.rs | 19 +++++++++++-------- .../src/traits/query/type_op/normalize.rs | 14 +++++++------- .../src/traits/query/type_op/outlives.rs | 4 ++-- .../traits/query/type_op/prove_predicate.rs | 4 ++-- .../src/traits/query/type_op/subtype.rs | 4 ++-- .../src/implied_outlives_bounds.rs | 4 ++-- compiler/rustc_traits/src/type_op.rs | 4 ++-- 17 files changed, 55 insertions(+), 53 deletions(-) diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index b2693e6054674..51a84ce6cadea 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -27,6 +27,7 @@ use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::AssertKind; use rustc_middle::mir::*; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::adjustment::PointerCast; use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::subst::{SubstsRef, UserSubsts}; @@ -42,7 +43,7 @@ use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints; use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; -use rustc_trait_selection::traits::query::Fallible; + use rustc_trait_selection::traits::PredicateObligation; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; @@ -1133,7 +1134,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { sup: Ty<'tcx>, locations: Locations, category: ConstraintCategory<'tcx>, - ) -> Fallible<()> { + ) -> Result<(), NoSolution> { // Use this order of parameters because the sup type is usually the // "expected" type in diagnostics. self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category) @@ -1146,7 +1147,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { found: Ty<'tcx>, locations: Locations, category: ConstraintCategory<'tcx>, - ) -> Fallible<()> { + ) -> Result<(), NoSolution> { self.relate_types(expected, ty::Variance::Invariant, found, locations, category) } @@ -1158,7 +1159,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { user_ty: &UserTypeProjection, locations: Locations, category: ConstraintCategory<'tcx>, - ) -> Fallible<()> { + ) -> Result<(), NoSolution> { let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty; trace!(?annotated_type); let mut curr_projected_ty = PlaceTy::from_ty(annotated_type); diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 6f3451d56574e..8c4bfb2c6e0d3 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -3,11 +3,11 @@ use rustc_infer::infer::nll_relate::{TypeRelating, TypeRelatingDelegate}; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_infer::traits::PredicateObligations; use rustc_middle::mir::ConstraintCategory; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::relate::TypeRelation; use rustc_middle::ty::{self, Ty}; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; -use rustc_trait_selection::traits::query::Fallible; use crate::constraints::OutlivesConstraint; use crate::diagnostics::UniverseInfo; @@ -31,7 +31,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { b: Ty<'tcx>, locations: Locations, category: ConstraintCategory<'tcx>, - ) -> Fallible<()> { + ) -> Result<(), NoSolution> { TypeRelating::new( self.infcx, NllTypeRelatingDelegate::new(self, locations, category, UniverseInfo::relate(a, b)), @@ -48,7 +48,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { b: ty::SubstsRef<'tcx>, locations: Locations, category: ConstraintCategory<'tcx>, - ) -> Fallible<()> { + ) -> Result<(), NoSolution> { TypeRelating::new( self.infcx, NllTypeRelatingDelegate::new(self, locations, category, UniverseInfo::other()), diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index de9afbbcaabbd..88256c819f4d4 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -15,7 +15,7 @@ use crate::infer::canonical::{ use crate::infer::nll_relate::{TypeRelating, TypeRelatingDelegate}; use crate::infer::region_constraints::{Constraint, RegionConstraintData}; use crate::infer::{DefineOpaqueTypes, InferCtxt, InferOk, InferResult, NllRegionVariableOrigin}; -use crate::traits::query::{Fallible, NoSolution}; +use crate::traits::query::NoSolution; use crate::traits::{Obligation, ObligationCause, PredicateObligation}; use crate::traits::{PredicateObligations, TraitEngine, TraitEngineExt}; use rustc_data_structures::captures::Captures; @@ -57,7 +57,7 @@ impl<'tcx> InferCtxt<'tcx> { inference_vars: CanonicalVarValues<'tcx>, answer: T, fulfill_cx: &mut dyn TraitEngine<'tcx>, - ) -> Fallible> + ) -> Result, NoSolution> where T: Debug + TypeFoldable>, Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>, diff --git a/compiler/rustc_middle/src/traits/query.rs b/compiler/rustc_middle/src/traits/query.rs index c4f8718754f5f..eae5a280e114d 100644 --- a/compiler/rustc_middle/src/traits/query.rs +++ b/compiler/rustc_middle/src/traits/query.rs @@ -95,8 +95,6 @@ pub type CanonicalTypeOpNormalizeGoal<'tcx, T> = #[derive(Copy, Clone, Debug, HashStable, PartialEq, Eq)] pub struct NoSolution; -pub type Fallible = Result; - impl<'tcx> From> for NoSolution { fn from(_: TypeError<'tcx>) -> NoSolution { NoSolution diff --git a/compiler/rustc_trait_selection/src/infer.rs b/compiler/rustc_trait_selection/src/infer.rs index 142c20014a015..312bd38178fdd 100644 --- a/compiler/rustc_trait_selection/src/infer.rs +++ b/compiler/rustc_trait_selection/src/infer.rs @@ -5,7 +5,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_middle::arena::ArenaAllocatable; use rustc_middle::infer::canonical::{Canonical, CanonicalQueryResponse, QueryResponse}; -use rustc_middle::traits::query::Fallible; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_middle::ty::{GenericArg, ToPredicate}; use rustc_span::DUMMY_SP; @@ -82,8 +82,8 @@ pub trait InferCtxtBuilderExt<'tcx> { fn enter_canonical_trait_query( &mut self, canonical_key: &Canonical<'tcx, K>, - operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Fallible, - ) -> Fallible> + operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Result, + ) -> Result, NoSolution> where K: TypeFoldable>, R: Debug + TypeFoldable>, @@ -110,8 +110,8 @@ impl<'tcx> InferCtxtBuilderExt<'tcx> for InferCtxtBuilder<'tcx> { fn enter_canonical_trait_query( &mut self, canonical_key: &Canonical<'tcx, K>, - operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Fallible, - ) -> Fallible> + operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Result, + ) -> Result, NoSolution> where K: TypeFoldable>, R: Debug + TypeFoldable>, diff --git a/compiler/rustc_trait_selection/src/traits/engine.rs b/compiler/rustc_trait_selection/src/traits/engine.rs index 000427bbe83ec..2c5ffd664fe1d 100644 --- a/compiler/rustc_trait_selection/src/traits/engine.rs +++ b/compiler/rustc_trait_selection/src/traits/engine.rs @@ -14,11 +14,11 @@ use rustc_infer::infer::canonical::{ }; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk}; -use rustc_infer::traits::query::Fallible; use rustc_infer::traits::{ FulfillmentError, Obligation, ObligationCause, PredicateObligation, TraitEngineExt as _, }; use rustc_middle::arena::ArenaAllocatable; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::ToPredicate; use rustc_middle::ty::TypeFoldable; @@ -235,7 +235,7 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> { &self, inference_vars: CanonicalVarValues<'tcx>, answer: T, - ) -> Fallible> + ) -> Result, NoSolution> where T: Debug + TypeFoldable>, Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs index e6db96c9e5580..c61f5454ec52e 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs @@ -1,5 +1,5 @@ use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::query::Fallible; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; pub use rustc_middle::traits::query::type_op::AscribeUserType; @@ -17,7 +17,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for AscribeUserType<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_ascribe_user_type(canonicalized) } } diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs index 94464895f3b2e..6d8d2103f3904 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs @@ -1,10 +1,10 @@ use crate::infer::canonical::query_response; use crate::infer::InferCtxt; use crate::traits::query::type_op::TypeOpOutput; -use crate::traits::query::Fallible; use crate::traits::ObligationCtxt; use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::region_constraints::RegionConstraintData; +use rustc_middle::traits::query::NoSolution; use rustc_span::source_map::DUMMY_SP; use rustc_span::Span; @@ -18,7 +18,7 @@ pub struct CustomTypeOp { impl CustomTypeOp { pub fn new<'tcx, R>(closure: F, description: &'static str) -> Self where - F: FnOnce(&ObligationCtxt<'_, 'tcx>) -> Fallible, + F: FnOnce(&ObligationCtxt<'_, 'tcx>) -> Result, { CustomTypeOp { closure, description } } @@ -26,7 +26,7 @@ impl CustomTypeOp { impl<'tcx, F, R: fmt::Debug> super::TypeOp<'tcx> for CustomTypeOp where - F: FnOnce(&ObligationCtxt<'_, 'tcx>) -> Fallible, + F: FnOnce(&ObligationCtxt<'_, 'tcx>) -> Result, { type Output = R; /// We can't do any custom error reporting for `CustomTypeOp`, so @@ -59,7 +59,7 @@ impl fmt::Debug for CustomTypeOp { /// constraints that result, creating query-region-constraints. pub fn scrape_region_constraints<'tcx, Op: super::TypeOp<'tcx, Output = R>, R>( infcx: &InferCtxt<'tcx>, - op: impl FnOnce(&ObligationCtxt<'_, 'tcx>) -> Fallible, + op: impl FnOnce(&ObligationCtxt<'_, 'tcx>) -> Result, name: &'static str, span: Span, ) -> Result<(TypeOpOutput<'tcx, Op>, RegionConstraintData<'tcx>), ErrorGuaranteed> { diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs index 8c9b9610cb6ef..40f8ecfd4ce10 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs @@ -1,5 +1,5 @@ use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::query::Fallible; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; pub use rustc_middle::traits::query::type_op::Eq; @@ -17,7 +17,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for Eq<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_eq(canonicalized) } } diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs index 18d7c9b193601..26f0d554d3508 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs @@ -1,6 +1,6 @@ use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::query::Fallible; use rustc_infer::traits::query::OutlivesBound; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt}; #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable, Lift)] @@ -28,7 +28,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ImpliedOutlivesBounds<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible> { + ) -> Result, NoSolution> { // FIXME this `unchecked_map` is only necessary because the // query is defined as taking a `ParamEnvAnd`; it should // take an `ImpliedOutlivesBounds` instead diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs index a34ea3fb3dd30..6423265984804 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs @@ -2,11 +2,11 @@ use crate::infer::canonical::{ Canonical, CanonicalQueryResponse, OriginalQueryValues, QueryRegionConstraints, }; use crate::infer::{InferCtxt, InferOk}; -use crate::traits::query::Fallible; use crate::traits::ObligationCause; use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::canonical::Certainty; use rustc_infer::traits::PredicateObligations; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_span::Span; @@ -79,18 +79,21 @@ pub trait QueryTypeOp<'tcx>: fmt::Debug + Copy + TypeFoldable> + 't fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible>; + ) -> Result, NoSolution>; fn fully_perform_into( query_key: ParamEnvAnd<'tcx, Self>, infcx: &InferCtxt<'tcx>, output_query_region_constraints: &mut QueryRegionConstraints<'tcx>, - ) -> Fallible<( - Self::QueryResponse, - Option>>, - PredicateObligations<'tcx>, - Certainty, - )> { + ) -> Result< + ( + Self::QueryResponse, + Option>>, + PredicateObligations<'tcx>, + Certainty, + ), + NoSolution, + > { if let Some(result) = QueryTypeOp::try_fast_path(infcx.tcx, &query_key) { return Ok((result, None, vec![], Certainty::Proven)); } diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs index 5b216c0769236..776c74fdfae4b 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs @@ -1,5 +1,5 @@ use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::query::Fallible; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{self, Lift, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; use std::fmt; @@ -19,7 +19,7 @@ where fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible> { + ) -> Result, NoSolution> { T::type_op_method(tcx, canonicalized) } } @@ -28,14 +28,14 @@ pub trait Normalizable<'tcx>: fmt::Debug + TypeFoldable> + Lift<'tc fn type_op_method( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize>>, - ) -> Fallible>; + ) -> Result, NoSolution>; } impl<'tcx> Normalizable<'tcx> for Ty<'tcx> { fn type_op_method( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_normalize_ty(canonicalized) } } @@ -44,7 +44,7 @@ impl<'tcx> Normalizable<'tcx> for ty::Predicate<'tcx> { fn type_op_method( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_normalize_predicate(canonicalized) } } @@ -53,7 +53,7 @@ impl<'tcx> Normalizable<'tcx> for ty::PolyFnSig<'tcx> { fn type_op_method( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_normalize_poly_fn_sig(canonicalized) } } @@ -62,7 +62,7 @@ impl<'tcx> Normalizable<'tcx> for ty::FnSig<'tcx> { fn type_op_method( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_normalize_fn_sig(canonicalized) } } diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs index 21ef4e24fdb05..7ce09bbdb7af3 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs @@ -1,6 +1,6 @@ use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; use crate::traits::query::dropck_outlives::{trivial_dropck_outlives, DropckOutlivesResult}; -use crate::traits::query::Fallible; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{ParamEnvAnd, Ty, TyCtxt}; #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable, Lift)] @@ -27,7 +27,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for DropckOutlives<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible> { + ) -> Result, NoSolution> { // Subtle: note that we are not invoking // `infcx.at(...).dropck_outlives(...)` here, but rather the // underlying `dropck_outlives` query. This same underlying diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs index baa2fbb6751c3..7c02f363960d7 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs @@ -1,5 +1,5 @@ use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::query::Fallible; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{self, ParamEnvAnd, TyCtxt}; pub use rustc_middle::traits::query::type_op::ProvePredicate; @@ -33,7 +33,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_prove_predicate(canonicalized) } } diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs index c51292eba14be..2f2b931afcff4 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs @@ -1,5 +1,5 @@ use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::query::Fallible; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; pub use rustc_middle::traits::query::type_op::Subtype; @@ -14,7 +14,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for Subtype<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, - ) -> Fallible> { + ) -> Result, NoSolution> { tcx.type_op_subtype(canonicalized) } } diff --git a/compiler/rustc_traits/src/implied_outlives_bounds.rs b/compiler/rustc_traits/src/implied_outlives_bounds.rs index 0c2bb863e1fe0..49cbf9efa7493 100644 --- a/compiler/rustc_traits/src/implied_outlives_bounds.rs +++ b/compiler/rustc_traits/src/implied_outlives_bounds.rs @@ -11,7 +11,7 @@ use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::source_map::DUMMY_SP; use rustc_trait_selection::infer::InferCtxtBuilderExt; -use rustc_trait_selection::traits::query::{CanonicalTyGoal, Fallible, NoSolution}; +use rustc_trait_selection::traits::query::{CanonicalTyGoal, NoSolution}; use rustc_trait_selection::traits::wf; use rustc_trait_selection::traits::ObligationCtxt; use smallvec::{smallvec, SmallVec}; @@ -37,7 +37,7 @@ fn compute_implied_outlives_bounds<'tcx>( ocx: &ObligationCtxt<'_, 'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>, -) -> Fallible>> { +) -> Result>, NoSolution> { let tcx = ocx.infcx.tcx; // Sometimes when we ask what it takes for T: WF, we get back that diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index b1cbd88ce27ea..faf985169deff 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -2,6 +2,7 @@ use rustc_hir as hir; use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::query::Providers; +use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::{DefiningAnchor, ObligationCauseCode}; use rustc_middle::ty::{self, FnSig, Lift, PolyFnSig, Ty, TyCtxt, TypeFoldable}; use rustc_middle::ty::{ParamEnvAnd, Predicate}; @@ -15,7 +16,6 @@ use rustc_trait_selection::traits::query::type_op::eq::Eq; use rustc_trait_selection::traits::query::type_op::normalize::Normalize; use rustc_trait_selection::traits::query::type_op::prove_predicate::ProvePredicate; use rustc_trait_selection::traits::query::type_op::subtype::Subtype; -use rustc_trait_selection::traits::query::{Fallible, NoSolution}; use rustc_trait_selection::traits::{Normalized, Obligation, ObligationCause, ObligationCtxt}; use std::fmt; @@ -160,7 +160,7 @@ fn type_op_eq<'tcx>( fn type_op_normalize<'tcx, T>( ocx: &ObligationCtxt<'_, 'tcx>, key: ParamEnvAnd<'tcx, Normalize>, -) -> Fallible +) -> Result where T: fmt::Debug + TypeFoldable> + Lift<'tcx>, { From a61f026182cb0fa5830156b0ef29c28bc4ccfe99 Mon Sep 17 00:00:00 2001 From: Brian M Date: Thu, 25 May 2023 11:24:00 -0700 Subject: [PATCH 13/15] Mac Catalyst: specify 14.0 deployment taregt in llvm_target --- compiler/rustc_target/src/spec/aarch64_apple_ios_macabi.rs | 2 +- compiler/rustc_target/src/spec/x86_64_apple_ios_macabi.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_target/src/spec/aarch64_apple_ios_macabi.rs b/compiler/rustc_target/src/spec/aarch64_apple_ios_macabi.rs index 2b135b6703481..e2df7e0bdcc79 100644 --- a/compiler/rustc_target/src/spec/aarch64_apple_ios_macabi.rs +++ b/compiler/rustc_target/src/spec/aarch64_apple_ios_macabi.rs @@ -2,7 +2,7 @@ use super::apple_base::{opts, Arch}; use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, TargetOptions}; pub fn target() -> Target { - let llvm_target = "arm64-apple-ios-macabi"; + let llvm_target = "arm64-apple-ios14.0-macabi"; let arch = Arch::Arm64_macabi; let mut base = opts("ios", arch); diff --git a/compiler/rustc_target/src/spec/x86_64_apple_ios_macabi.rs b/compiler/rustc_target/src/spec/x86_64_apple_ios_macabi.rs index 5a3e2a79bb9cc..9f3b0fab697e6 100644 --- a/compiler/rustc_target/src/spec/x86_64_apple_ios_macabi.rs +++ b/compiler/rustc_target/src/spec/x86_64_apple_ios_macabi.rs @@ -2,7 +2,7 @@ use super::apple_base::{opts, Arch}; use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; pub fn target() -> Target { - let llvm_target = "x86_64-apple-ios-macabi"; + let llvm_target = "x86_64-apple-ios14.0-macabi"; let arch = Arch::X86_64_macabi; let mut base = opts("ios", arch); From b37cdc67bef4de5dde9f5cffeb8f7a2592fdde4b Mon Sep 17 00:00:00 2001 From: Obei Sideg Date: Thu, 25 May 2023 15:43:41 +0300 Subject: [PATCH 14/15] Add test for RPIT defined with different hidden types with different substs --- .../multiple-defining-usages-in-body.rs | 12 +++++++++ .../multiple-defining-usages-in-body.stderr | 26 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 tests/ui/impl-trait/multiple-defining-usages-in-body.rs create mode 100644 tests/ui/impl-trait/multiple-defining-usages-in-body.stderr diff --git a/tests/ui/impl-trait/multiple-defining-usages-in-body.rs b/tests/ui/impl-trait/multiple-defining-usages-in-body.rs new file mode 100644 index 0000000000000..c3a6f09f86d93 --- /dev/null +++ b/tests/ui/impl-trait/multiple-defining-usages-in-body.rs @@ -0,0 +1,12 @@ +trait Trait {} +impl Trait for () {} + +fn foo() -> impl Trait { + //~^ WARN function cannot return without recursing [unconditional_recursion] + let a: T = foo::(); + //~^ ERROR concrete type differs from previous defining opaque type use + loop {} + let _: T = foo::(); +} + +fn main() {} diff --git a/tests/ui/impl-trait/multiple-defining-usages-in-body.stderr b/tests/ui/impl-trait/multiple-defining-usages-in-body.stderr new file mode 100644 index 0000000000000..06991749bfad1 --- /dev/null +++ b/tests/ui/impl-trait/multiple-defining-usages-in-body.stderr @@ -0,0 +1,26 @@ +warning: function cannot return without recursing + --> $DIR/multiple-defining-usages-in-body.rs:4:1 + | +LL | fn foo() -> impl Trait { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot return without recursing +LL | +LL | let a: T = foo::(); + | ------------- recursive call site + | + = help: a `loop` may express intention better if this is on purpose + = note: `#[warn(unconditional_recursion)]` on by default + +error: concrete type differs from previous defining opaque type use + --> $DIR/multiple-defining-usages-in-body.rs:6:16 + | +LL | let a: T = foo::(); + | ^^^^^^^^^^^^^ expected `U`, got `T` + | +note: previous use here + --> $DIR/multiple-defining-usages-in-body.rs:9:16 + | +LL | let _: T = foo::(); + | ^^^^^^^^^^^^^ + +error: aborting due to previous error; 1 warning emitted + From e6b99a6521535d79a53b2111f236f82fae0b123e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 26 May 2023 07:28:02 +1000 Subject: [PATCH 15/15] Add struct for the return type of `place_root_mono_items`. As per review request. --- .../rustc_monomorphize/src/partitioning/default.rs | 7 ++++--- compiler/rustc_monomorphize/src/partitioning/mod.rs | 12 +++++++++--- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_monomorphize/src/partitioning/default.rs b/compiler/rustc_monomorphize/src/partitioning/default.rs index 362e21eaecd0a..603b3ddc106e9 100644 --- a/compiler/rustc_monomorphize/src/partitioning/default.rs +++ b/compiler/rustc_monomorphize/src/partitioning/default.rs @@ -15,7 +15,7 @@ use rustc_span::symbol::Symbol; use super::PartitioningCx; use crate::collector::InliningMap; -use crate::partitioning::{MonoItemPlacement, Partition}; +use crate::partitioning::{MonoItemPlacement, Partition, PlacedRootMonoItems}; pub struct DefaultPartitioning; @@ -24,7 +24,7 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { &mut self, cx: &PartitioningCx<'_, 'tcx>, mono_items: &mut I, - ) -> (Vec>, FxHashSet>, FxHashSet>) + ) -> PlacedRootMonoItems<'tcx> where I: Iterator>, { @@ -89,7 +89,8 @@ impl<'tcx> Partition<'tcx> for DefaultPartitioning { codegen_units.insert(codegen_unit_name, CodegenUnit::new(codegen_unit_name)); } - (codegen_units.into_values().collect(), roots, internalization_candidates) + let codegen_units = codegen_units.into_values().collect(); + PlacedRootMonoItems { codegen_units, roots, internalization_candidates } } fn merge_codegen_units( diff --git a/compiler/rustc_monomorphize/src/partitioning/mod.rs b/compiler/rustc_monomorphize/src/partitioning/mod.rs index ac161bc82d911..d0b23ca9ea444 100644 --- a/compiler/rustc_monomorphize/src/partitioning/mod.rs +++ b/compiler/rustc_monomorphize/src/partitioning/mod.rs @@ -128,7 +128,7 @@ impl<'tcx> Partition<'tcx> for Partitioner { &mut self, cx: &PartitioningCx<'_, 'tcx>, mono_items: &mut I, - ) -> (Vec>, FxHashSet>, FxHashSet>) + ) -> PlacedRootMonoItems<'tcx> where I: Iterator>, { @@ -188,12 +188,18 @@ struct PartitioningCx<'a, 'tcx> { inlining_map: &'a InliningMap<'tcx>, } +pub struct PlacedRootMonoItems<'tcx> { + codegen_units: Vec>, + roots: FxHashSet>, + internalization_candidates: FxHashSet>, +} + trait Partition<'tcx> { fn place_root_mono_items( &mut self, cx: &PartitioningCx<'_, 'tcx>, mono_items: &mut I, - ) -> (Vec>, FxHashSet>, FxHashSet>) + ) -> PlacedRootMonoItems<'tcx> where I: Iterator>; @@ -247,7 +253,7 @@ where // In the first step, we place all regular monomorphizations into their // respective 'home' codegen unit. Regular monomorphizations are all // functions and statics defined in the local crate. - let (mut codegen_units, roots, internalization_candidates) = { + let PlacedRootMonoItems { mut codegen_units, roots, internalization_candidates } = { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_roots"); partitioner.place_root_mono_items(cx, mono_items) };