diff --git a/compiler/rustc_borrowck/src/polonius/constraints.rs b/compiler/rustc_borrowck/src/polonius/constraints.rs index ce32b6ee99012..637068a9799d7 100644 --- a/compiler/rustc_borrowck/src/polonius/constraints.rs +++ b/compiler/rustc_borrowck/src/polonius/constraints.rs @@ -3,6 +3,7 @@ use rustc_index::interval::SparseIntervalMatrix; use rustc_middle::mir::{Body, Location}; use rustc_middle::ty::RegionVid; use rustc_mir_dataflow::points::PointIndex; +use tracing::debug; use crate::BorrowSet; use crate::constraints::OutlivesConstraint; @@ -253,6 +254,7 @@ fn compute_forward_successor( // 2. Otherwise, gather the edges due to explicit region liveness, when applicable. if !live_regions.contains(region, next_point) { + debug!(?region, ?next_point, "region isn't live at successor"); return None; } @@ -272,6 +274,8 @@ fn compute_forward_successor( .flatten() .unwrap_or(ConstraintDirection::Bidirectional); + debug!(?direction); + match direction { ConstraintDirection::Backward => { // Contravariant cases: loans flow in the inverse direction, but we're only interested @@ -300,6 +304,7 @@ fn compute_backward_successor( // Liveness flows into the regions live at the next point. So, in a backwards view, we'll link // the region from the current point, if it's live there, to the previous point. if !live_regions.contains(region, current_point) { + debug!(?region, ?current_point, "region isn't live at current point"); return None; } diff --git a/compiler/rustc_borrowck/src/polonius/dump.rs b/compiler/rustc_borrowck/src/polonius/dump.rs index 5285f724b02ec..e0f4c9ff98eca 100644 --- a/compiler/rustc_borrowck/src/polonius/dump.rs +++ b/compiler/rustc_borrowck/src/polonius/dump.rs @@ -10,11 +10,16 @@ use rustc_session::config::MirIncludeSpans; use crate::borrow_set::BorrowSet; use crate::constraints::OutlivesConstraint; +use crate::dataflow::BorrowIndex; use crate::polonius::{LocalizedConstraintGraphVisitor, LocalizedNode, PoloniusContext}; use crate::region_infer::values::LivenessValues; use crate::type_check::Locations; use crate::{BorrowckInferCtxt, ClosureRegionRequirements, RegionInferenceContext}; +/// The polonius MIR dump template: a regular HTML file for easy editing, with special dummy +/// sections to be replaced by real contents. +const TEMPLATE: &str = include_str!("./dump/polonius-mir-dump.template.html"); + /// `-Zdump-mir=polonius` dumps MIR annotated with NLL and polonius specific information. pub(crate) fn dump_polonius_mir<'tcx>( infcx: &BorrowckInferCtxt<'tcx>, @@ -36,7 +41,7 @@ pub(crate) fn dump_polonius_mir<'tcx>( // If we have a polonius graph to dump along the rest of the MIR and NLL info, we extract its // constraints here. - let mut collector = LocalizedOutlivesConstraintCollector { constraints: Vec::new() }; + let mut collector = MirDumpCollector::default(); if let Some(graph) = &polonius_context.graph { graph.traverse( body, @@ -72,7 +77,7 @@ pub(crate) fn dump_polonius_mir<'tcx>( let _ = try { let mut file = dumper.create_dump_file("html", body)?; - emit_polonius_dump(&dumper, body, regioncx, borrow_set, &collector.constraints, &mut file)?; + emit_polonius_dump(&dumper, body, regioncx, borrow_set, &collector, &mut file)?; }; } @@ -84,12 +89,19 @@ struct LocalizedOutlivesConstraint { to: PointIndex, } -/// Visitor to record constraints encountered when traversing the localized constraint graph. -struct LocalizedOutlivesConstraintCollector { +/// Visitor to record constraints encountered when traversing the localized constraint graph, as +/// well as the reachability of each loan. +#[derive(Default)] +struct MirDumpCollector { constraints: Vec, + reachability: FxIndexMap>, } -impl LocalizedConstraintGraphVisitor for LocalizedOutlivesConstraintCollector { +impl LocalizedConstraintGraphVisitor for MirDumpCollector { + fn on_node_traversed(&mut self, loan: BorrowIndex, node: LocalizedNode) { + self.reachability.entry(loan).or_default().push(node); + } + fn on_successor_discovered(&mut self, current_node: LocalizedNode, successor: LocalizedNode) { self.constraints.push(LocalizedOutlivesConstraint { source: current_node.region, @@ -111,75 +123,77 @@ fn emit_polonius_dump<'tcx>( body: &Body<'tcx>, regioncx: &RegionInferenceContext<'tcx>, borrow_set: &BorrowSet<'tcx>, - localized_outlives_constraints: &[LocalizedOutlivesConstraint], + collector: &MirDumpCollector, out: &mut dyn io::Write, ) -> io::Result<()> { - // Prepare the HTML dump file prologue. - writeln!(out, "")?; - writeln!(out, "")?; - writeln!(out, "Polonius MIR dump")?; - writeln!(out, "")?; - - // Section 1: the NLL + Polonius MIR. - writeln!(out, "
")?; - writeln!(out, "Raw MIR dump")?; - writeln!(out, "
")?;
-    emit_html_mir(dumper, body, out)?;
-    writeln!(out, "
")?; - writeln!(out, "
")?; - - // Section 2: mermaid visualization of the polonius constraint graph. - writeln!(out, "
")?; - writeln!(out, "Polonius constraint graph")?; - writeln!(out, "
")?;
-    let edge_count = emit_mermaid_constraint_graph(
-        borrow_set,
-        regioncx.liveness_constraints(),
-        &localized_outlives_constraints,
-        out,
-    )?;
-    writeln!(out, "
")?; - writeln!(out, "
")?; - - // Section 3: mermaid visualization of the CFG. - writeln!(out, "
")?; - writeln!(out, "Control-flow graph")?; - writeln!(out, "
")?;
-    emit_mermaid_cfg(body, out)?;
-    writeln!(out, "
")?; - writeln!(out, "
")?; - - // Section 4: mermaid visualization of the NLL region graph. - writeln!(out, "
")?; - writeln!(out, "NLL regions")?; - writeln!(out, "
")?;
-    emit_mermaid_nll_regions(dumper.tcx(), regioncx, out)?;
-    writeln!(out, "
")?; - writeln!(out, "
")?; - - // Section 5: mermaid visualization of the NLL SCC graph. - writeln!(out, "
")?; - writeln!(out, "NLL SCCs")?; - writeln!(out, "
")?;
-    emit_mermaid_nll_sccs(dumper.tcx(), regioncx, out)?;
-    writeln!(out, "
")?; - writeln!(out, "
")?; - - // Finalize the dump with the HTML epilogue. - writeln!( - out, - "" - )?; - writeln!(out, "")?; - writeln!(out, "")?; - writeln!(out, "")?; + let mut edge_count = 0; + + // We replace the dummy $SECTION tokens from the HTML polonius dump template, and emit the + // result into the given writer. + for chunk in TEMPLATE.split("$SECTION") { + match chunk.strip_prefix("_") { + None => { + // We're at the beginning of the template: this is the prologue to emit as-is. + writeln!(out, "{}", chunk)?; + } + Some(section) => { + // This is the start of a prefixed section, we look for its identifier. + let dummy_section_end = section + .find("<") + .expect("the template section end boundary needs to be present"); + let section_identifier = section[..dummy_section_end].trim(); + + // Emit the real section instead of the dummy token. + match section_identifier { + "MIR" => { + emit_html_mir(dumper, body, out)?; + } + "POLONIUS_CONSTRAINTS" => { + edge_count = emit_mermaid_constraint_graph( + borrow_set, + regioncx.liveness_constraints(), + &collector.constraints, + out, + )?; + } + "POLONIUS_REACHABILITY" => { + emit_loan_reachability( + borrow_set, + regioncx.liveness_constraints(), + &collector.reachability, + out, + )?; + } + "CFG" => { + emit_mermaid_cfg(body, out)?; + } + "NLL_CONSTRAINTS" => { + emit_mermaid_nll_regions(dumper.tcx(), regioncx, out)?; + } + "NLL_SCCS" => { + emit_mermaid_nll_sccs(dumper.tcx(), regioncx, out)?; + } + "INITIALIZATION" => { + writeln!(out, "")?; + } + + _ => { + unreachable!("unexpected dummy section identifier {:?}", section_identifier) + } + } + + // And finally, emit the contents that followed the dummy token. + writeln!(out, "{}", §ion[dummy_section_end..])?; + } + } + } Ok(()) } @@ -431,15 +445,9 @@ fn emit_mermaid_constraint_graph<'tcx>( localized_outlives_constraints: &[LocalizedOutlivesConstraint], out: &mut dyn io::Write, ) -> io::Result { - let location_name = |location: Location| { - // A MIR location looks like `bb5[2]`. As that is not a syntactically valid mermaid node id, - // transform it into `BB5_2`. - format!("BB{}_{}", location.block.index(), location.statement_index) - }; - let region_name = |region: RegionVid| format!("'{}", region.index()); - let node_name = |region: RegionVid, point: PointIndex| { + let node_label = |region: RegionVid, point: PointIndex| { let location = liveness.location_from_point(point); - format!("{}_{}", region_name(region), location_name(location)) + node_name(region, location) }; // The mermaid chart type: a top-down flowchart, which supports subgraphs. @@ -474,7 +482,7 @@ fn emit_mermaid_constraint_graph<'tcx>( for (region, points) in points_per_region { writeln!(out, " subgraph \"{}\"", region_name(region))?; for point in points { - writeln!(out, " {}", node_name(region, point))?; + writeln!(out, " {}", node_label(region, point))?; } writeln!(out, " end\n")?; } @@ -485,8 +493,8 @@ fn emit_mermaid_constraint_graph<'tcx>( writeln!( out, " {} --> {}", - node_name(constraint.source, constraint.from), - node_name(constraint.target, constraint.to), + node_label(constraint.source, constraint.from), + node_label(constraint.target, constraint.to), )?; } @@ -495,3 +503,70 @@ fn emit_mermaid_constraint_graph<'tcx>( let edge_count = borrow_set.len() + localized_outlives_constraints.len(); Ok(edge_count) } + +/// Emits the reachability of loans: a list of all nodes reached while traversing the polonius +/// constraint graph. +fn emit_loan_reachability( + borrow_set: &BorrowSet<'_>, + liveness: &LivenessValues, + reachability: &FxIndexMap>, + out: &mut dyn io::Write, +) -> io::Result<()> { + for (loan, _) in borrow_set.iter_enumerated() { + let Some(reachability) = reachability.get(&loan) else { + continue; + }; + let loan = format!("L{}", loan.index()); + + // The button to display the loan trace. The javascript event listener is hooked up in the + // template itself. + writeln!( + out, + "
" + )?; + + // The actual trace contents, hidden by default. + writeln!(out, "")?; + } + + Ok(()) +} + +fn region_name(region: RegionVid) -> String { + format!("'{}", region.index()) +} +/// A MIR location looks like `bb5[2]`. As that is not a syntactically valid mermaid node id, +/// transform it into `BB5_2`. +fn location_name(location: Location) -> String { + format!("BB{}_{}", location.block.index(), location.statement_index) +} +fn node_name(region: RegionVid, location: Location) -> String { + format!("{}_{}", region_name(region), location_name(location)) +} diff --git a/compiler/rustc_borrowck/src/polonius/dump/polonius-mir-dump.template.html b/compiler/rustc_borrowck/src/polonius/dump/polonius-mir-dump.template.html new file mode 100644 index 0000000000000..e2b9b412963a2 --- /dev/null +++ b/compiler/rustc_borrowck/src/polonius/dump/polonius-mir-dump.template.html @@ -0,0 +1,86 @@ + + + +Polonius MIR dump + + + + + + +
+
Raw MIR dump
+
$SECTION_MIR
+
+ + +
+
Polonius constraint graph
+
$SECTION_POLONIUS_CONSTRAINTS
+
+ + +
+
Loan Traces
+ $SECTION_POLONIUS_REACHABILITY +
+ + +
+
Control-flow graph
+
$SECTION_CFG
+
+ + +
+
NLL regions
+
$SECTION_NLL_CONSTRAINTS
+
+ + +
+
NLL SCCs
+
$SECTION_NLL_SCCS
+
+ + +$SECTION_INITIALIZATION + + + diff --git a/compiler/rustc_borrowck/src/polonius/legacy/mod.rs b/compiler/rustc_borrowck/src/polonius/legacy/mod.rs index 0ae3ff3c04790..1aae724266c6f 100644 --- a/compiler/rustc_borrowck/src/polonius/legacy/mod.rs +++ b/compiler/rustc_borrowck/src/polonius/legacy/mod.rs @@ -192,7 +192,7 @@ pub(crate) fn emit_drop_facts<'tcx>( debug!("emit_drop_facts(local={:?}, kind={:?}", local, kind); let Some(facts) = facts.as_mut() else { return }; let _prof_timer = tcx.prof.generic_activity("polonius_fact_generation"); - tcx.for_each_free_region(kind, |drop_live_region| { + tcx.for_each_free_region(&kind, |drop_live_region| { let region_vid = universal_regions.to_region_vid(drop_live_region); facts.drop_of_var_derefs_origin.push((local, region_vid.into())); }); diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs index dc8e8e077be95..7f3ed58db6c77 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs @@ -5,8 +5,7 @@ use rustc_infer::infer::canonical::QueryRegionConstraints; use rustc_infer::traits::TraitErrors; use rustc_middle::mir::{BasicBlock, Body, ConstraintCategory, Local, Location}; use rustc_middle::traits::query::DropckOutlivesResult; -use rustc_middle::ty::relate::Relate; -use rustc_middle::ty::{Ty, TyCtxt, TypeVisitable, TypeVisitableExt}; +use rustc_middle::ty::{GenericArg, Ty, TypeVisitable, TypeVisitableExt}; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex}; use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex}; @@ -536,7 +535,8 @@ impl<'tcx> LivenessContext<'_, '_, 'tcx> { /// points `live_at`. fn add_use_live_facts_for(&mut self, value: Ty<'tcx>, live_at: &IntervalSet) { debug!("add_use_live_facts_for(value={:?})", value); - Self::make_all_regions_live(self.location_map, self.typeck, value, live_at); + Self::record_region_variance(self.typeck, value.into()); + Self::make_all_regions_live(self.location_map, self.typeck, value.into(), live_at); } /// Some variable with type `live_ty` is "drop live" at `location` @@ -577,6 +577,9 @@ impl<'tcx> LivenessContext<'_, '_, 'tcx> { } } + // Since the entire dropped local is live, record the variance of its regions. + Self::record_region_variance(self.typeck, dropped_ty.into()); + // All things in the `outlives` array may be touched by // the destructor and must be live at this point. for &kind in &drop_data.dropck_result.kinds { @@ -591,10 +594,25 @@ impl<'tcx> LivenessContext<'_, '_, 'tcx> { } } + /// `live_kind` is the type of a (use- or drop-) live local. + /// Record the variance of any region(s) appearing in it for Polonius. Does + /// nothing if Polonius is not active. + fn record_region_variance(typeck: &mut TypeChecker<'_, 'tcx>, live_kind: GenericArg<'tcx>) { + // When using `-Zpolonius=next`, we record the variance of each live region. + if let Some(polonius_context) = typeck.polonius_context.as_mut() { + record_live_region_variance( + typeck.infcx.tcx, + &mut polonius_context.live_region_variances, + typeck.universal_regions, + live_kind, + ); + } + } + fn make_all_regions_live( location_map: &DenseLocationMap, typeck: &mut TypeChecker<'_, 'tcx>, - value: impl TypeVisitable> + Relate>, + value: GenericArg<'tcx>, live_at: &IntervalSet, ) { debug!("make_all_regions_live(value={:?})", value); @@ -608,20 +626,10 @@ impl<'tcx> LivenessContext<'_, '_, 'tcx> { param_env: typeck.infcx.param_env, op: |r| { let live_region_vid = typeck.universal_regions.to_region_vid(r); - typeck.constraints.liveness_constraints.add_points(live_region_vid, live_at); }, }); - - // When using `-Zpolonius=next`, we record the variance of each live region. - if let Some(polonius_context) = typeck.polonius_context.as_mut() { - record_live_region_variance( - typeck.infcx.tcx, - &mut polonius_context.live_region_variances, - typeck.universal_regions, - value, - ); - } + Self::record_region_variance(typeck, value); } } diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 972a4cc8de83e..677db66530ecb 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -110,8 +110,7 @@ impl TestHarnessGenerator<'_> { Some(node_id), ); for test in &mut tests { - // See the comment on `mk_main` for why we're using - // `apply_mark` directly. + // See the comment on `add_main` for why we're using `apply_mark` directly. test.ident.span = test.ident.span.apply_mark(expn_id.to_expn_id(), Transparency::Opaque); } @@ -127,7 +126,7 @@ impl<'a> MutVisitor for TestHarnessGenerator<'a> { self.add_test_cases(ast::CRATE_NODE_ID, c.spans.inner_span, prev_tests); // Create a main function to run our tests - c.items.push(mk_main(&mut self.cx)); + add_main(&mut self.cx, c); } fn visit_item(&mut self, item: &mut ast::Item) { @@ -288,16 +287,20 @@ fn generate_test_harness( /// [`TestCtxt::reexport_test_harness_main`] provides a different name for the `main` /// function and [`TestCtxt::test_runner`] provides a path that replaces /// `test::test_main_env_args`. -fn mk_main(cx: &mut TestCtxt<'_>) -> Box { +fn add_main(cx: &mut TestCtxt<'_>, c: &mut ast::Crate) { let sp = cx.def_site; let ecx = &cx.ext_cx; + // `sp` has def-site hygiene so should not clash with user-defined names. let test_ident = Ident::new(sym::test, sp); - let runner_name = - if cx.panic_strategy.unwinds() { "test_main_env_args" } else { "test_main_env_args_abort" }; - // test::test_main_env_args(...) let mut test_runner = cx.test_runner.clone().unwrap_or_else(|| { + // Built-in runner name depends on panic strategy. + let runner_name = if cx.panic_strategy.unwinds() { + "test_main_env_args" + } else { + "test_main_env_args_abort" + }; ecx.path(sp, vec![test_ident, Ident::from_str_and_span(runner_name, sp)]) }); @@ -308,10 +311,8 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> Box { let call_test_main = ecx.stmt_expr(call_test_main); // extern crate test - let test_extern_stmt = ecx.stmt_item( - sp, - ecx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident)), - ); + let test_extern_stmt = + ecx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident)); // #[rustc_main] let main_attr = ecx.attr_word(sym::rustc_main, sp); @@ -320,20 +321,18 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> Box { // #[doc(hidden)] let doc_hidden_attr = ecx.attr_nested_word(sym::doc, sym::hidden, sp); - // pub fn main() { ... } - // FIXME: it would be nice if we could use `std::process::ExitCode` as return type here, and - // remove all early-exit from libtest itself. Or rather, it should be `test::ExitCode` so we - // don't depend on whatever `std` may be. This needs the `extern crate test` to be *outside* - // `main`. But naively moving it out causes ICEs that give no hint as to what is wrong. - let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(ThinVec::new())); - - // If no test runner is provided we need to import the test crate - let main_body = if cx.test_runner.is_none() { - ecx.block(sp, thin_vec![test_extern_stmt, call_test_main]) + // pub fn main() -> ExitCode { ... } + let main_ret_ty = if cx.test_runner.is_none() { + // Built-in runner has return type `ExitCode`. + let exit_code_path = vec![test_ident, Ident::from_str_and_span("ExitCode", sp)]; + ecx.ty(sp, ast::TyKind::Path(None, ecx.path(sp, exit_code_path))) } else { - ecx.block(sp, thin_vec![call_test_main]) + // User-defined runners have return type `()`. + ecx.ty(sp, ast::TyKind::Tup(ThinVec::new())) }; + let main_body = ecx.block(sp, thin_vec![call_test_main]); + let decl = ecx.fn_decl(ThinVec::new(), ast::FnRetTy::Ty(main_ret_ty)); let sig = ast::FnSig { decl, header: ast::FnHeader::default(), span: sp }; let defaultness = ast::Defaultness::Implicit; @@ -365,8 +364,8 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> Box { }); // Integrate the new item into existing module structures. - let main = AstFragment::Items(smallvec![main]); - cx.ext_cx.monotonic_expander().fully_expand_fragment(main).make_items().pop().unwrap() + let items = AstFragment::Items(smallvec![test_extern_stmt, main]); + c.items.extend(cx.ext_cx.monotonic_expander().fully_expand_fragment(items).make_items()); } /// Creates a slice containing every test like so: diff --git a/library/core/src/fmt/builders.rs b/library/core/src/fmt/builders.rs index ceec98c8659fb..6a44f9ef5374e 100644 --- a/library/core/src/fmt/builders.rs +++ b/library/core/src/fmt/builders.rs @@ -183,6 +183,34 @@ impl<'a, 'b: 'a> DebugStruct<'a, 'b> { /// /// This method is equivalent to [`DebugStruct::field`], but formats the /// value using a provided closure rather than by calling [`Debug::fmt`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(debug_closure_helpers)] + /// + /// use std::fmt; + /// + /// struct Bar { + /// bar: i32, + /// another: String, + /// } + /// + /// impl fmt::Debug for Bar { + /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + /// fmt.debug_struct("Bar") + /// // Print `bar` as a hex value + /// .field_with("bar", |fmt| write!(fmt, "{:#010x}", &self.bar)) + /// .field("another", &self.another) + /// .finish() + /// } + /// } + /// + /// assert_eq!( + /// format!("{:?}", Bar { bar: 10, another: "Hello World".to_string() }), + /// r#"Bar { bar: 0x0000000a, another: "Hello World" }"#, + /// ); + /// ``` #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub fn field_with(&mut self, name: &str, value_fmt: F) -> &mut Self where @@ -376,6 +404,31 @@ impl<'a, 'b: 'a> DebugTuple<'a, 'b> { /// /// This method is equivalent to [`DebugTuple::field`], but formats the /// value using a provided closure rather than by calling [`Debug::fmt`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(debug_closure_helpers)] + /// + /// use std::fmt; + /// + /// struct Foo(i32, String); + /// + /// impl fmt::Debug for Foo { + /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + /// fmt.debug_tuple("Foo") + /// // Print the first field as a hex value + /// .field_with(|fmt| write!(fmt, "{:#010x}", &self.0)) + /// .field(&self.1) + /// .finish() + /// } + /// } + /// + /// assert_eq!( + /// format!("{:?}", Foo(10, "Hello World".to_string())), + /// r#"Foo(0x0000000a, "Hello World")"#, + /// ); + /// ``` #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub fn field_with(&mut self, value_fmt: F) -> &mut Self where @@ -582,6 +635,31 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// /// This method is equivalent to [`DebugSet::entry`], but formats the /// entry using a provided closure rather than by calling [`Debug::fmt`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(debug_closure_helpers)] + /// + /// use std::fmt; + /// + /// struct Foo(Vec, Vec); + /// + /// impl fmt::Debug for Foo { + /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + /// fmt.debug_set() + /// .entry(&self.0) + /// // Print the second member as a set + /// .entry_with(|fmt| fmt.debug_set().entries(&self.1).finish()) + /// .finish() + /// } + /// } + /// + /// assert_eq!( + /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])), + /// "{[10, 11], {12, 13}}", + /// ); + /// ``` #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub fn entry_with(&mut self, entry_fmt: F) -> &mut Self where @@ -774,6 +852,31 @@ impl<'a, 'b: 'a> DebugList<'a, 'b> { /// /// This method is equivalent to [`DebugList::entry`], but formats the /// entry using a provided closure rather than by calling [`Debug::fmt`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(debug_closure_helpers)] + /// + /// use std::fmt; + /// + /// struct Foo(Vec, Vec); + /// + /// impl fmt::Debug for Foo { + /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + /// fmt.debug_list() + /// .entry(&self.0) + /// // Print the second member as a set + /// .entry_with(|fmt| fmt.debug_set().entries(&self.1).finish()) + /// .finish() + /// } + /// } + /// + /// assert_eq!( + /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])), + /// "[[10, 11], {12, 13}]", + /// ); + /// ``` #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub fn entry_with(&mut self, entry_fmt: F) -> &mut Self where @@ -1032,6 +1135,34 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// /// This method is equivalent to [`DebugMap::key`], but formats the /// key using a provided closure rather than by calling [`Debug::fmt`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(debug_closure_helpers)] + /// + /// use std::fmt; + /// + /// struct Foo(Vec<(String, i32)>); + /// + /// impl fmt::Debug for Foo { + /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + /// let mut map = fmt.debug_map(); + /// for (k, v) in &self.0 { + /// // Append "entry" to each key + /// map.key_with(|fmt| write!(fmt, "entry {k}")); + /// // Write values as hex + /// map.value_with(|fmt| write!(fmt, "{v:#010x}")); + /// } + /// map.finish() + /// } + /// } + /// + /// assert_eq!( + /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])), + /// r#"{entry A: 0x0000000a, entry B: 0x0000000b}"#, + /// ); + /// ``` #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub fn key_with(&mut self, key_fmt: F) -> &mut Self where @@ -1097,6 +1228,34 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// /// This method is equivalent to [`DebugMap::value`], but formats the /// value using a provided closure rather than by calling [`Debug::fmt`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(debug_closure_helpers)] + /// + /// use std::fmt; + /// + /// struct Foo(Vec<(String, i32)>); + /// + /// impl fmt::Debug for Foo { + /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + /// let mut map = fmt.debug_map(); + /// for (k, v) in &self.0 { + /// // Append "entry" to each key + /// map.key_with(|fmt| write!(fmt, "entry {k}")); + /// // Write values as hex + /// map.value_with(|fmt| write!(fmt, "{v:#010x}")); + /// } + /// map.finish() + /// } + /// } + /// + /// assert_eq!( + /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])), + /// r#"{entry A: 0x0000000a, entry B: 0x0000000b}"#, + /// ); + /// ``` #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub fn value_with(&mut self, value_fmt: F) -> &mut Self where diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index 473b185d24652..1dbd11426e57e 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -90,6 +90,8 @@ impl RawWaker { /// pointers to *different* functions can compare equal (since identical functions can be /// deduplicated within a codegen unit). /// +/// This struct is guaranteed to be aligned to at least 8 bytes. +/// /// # Thread safety /// If the [`RawWaker`] will be used to construct a [`Waker`] then /// these functions must all be thread-safe (even though [`RawWaker`] is @@ -106,6 +108,8 @@ impl RawWaker { #[stable(feature = "futures_api", since = "1.36.0")] #[allow(unpredictable_function_pointer_comparisons)] #[derive(PartialEq, Copy, Clone, Debug)] +// For bit-stuffing pointers we guarantee align >= 8. +#[repr(align(8))] pub struct RawWakerVTable { /// This function will be called when the [`RawWaker`] gets cloned, e.g. when /// the [`Waker`] in which the [`RawWaker`] is stored gets cloned. diff --git a/library/std/src/os/windows/process.rs b/library/std/src/os/windows/process.rs index 104c5dba70b68..3e1fe13ee6fc2 100644 --- a/library/std/src/os/windows/process.rs +++ b/library/std/src/os/windows/process.rs @@ -188,7 +188,7 @@ pub impl(self) trait CommandExt { /// /// /// [1]: - #[unstable(feature = "windows_process_extensions_show_window", issue = "127544")] + #[stable(feature = "windows_process_extensions_show_window", since = "CURRENT_RUSTC_VERSION")] fn show_window(&mut self, cmd_show: u16) -> &mut process::Command; /// Forces all arguments to be wrapped in quote (`"`) characters. @@ -451,14 +451,23 @@ impl CommandExt for process::Command { } } -#[unstable(feature = "windows_process_extensions_main_thread_handle", issue = "96723")] +#[stable( + feature = "windows_process_extensions_main_thread_handle", + since = "CURRENT_RUSTC_VERSION" +)] pub impl(self) trait ChildExt { /// Extracts the main thread raw handle, without taking ownership - #[unstable(feature = "windows_process_extensions_main_thread_handle", issue = "96723")] + #[stable( + feature = "windows_process_extensions_main_thread_handle", + since = "CURRENT_RUSTC_VERSION" + )] fn main_thread_handle(&self) -> BorrowedHandle<'_>; } -#[unstable(feature = "windows_process_extensions_main_thread_handle", issue = "96723")] +#[stable( + feature = "windows_process_extensions_main_thread_handle", + since = "CURRENT_RUSTC_VERSION" +)] impl ChildExt for process::Child { fn main_thread_handle(&self) -> BorrowedHandle<'_> { self.handle.main_thread_handle() diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 6414a235698b8..20ea03d36eb0e 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -2206,6 +2206,7 @@ impl crate::error::Error for ExitStatusError {} /// ``` #[derive(Clone, Copy, Debug, PartialEq)] #[stable(feature = "process_exitcode", since = "1.61.0")] +#[must_use] pub struct ExitCode(imp::ExitCode); #[stable(feature = "process_exitcode", since = "1.61.0")] diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 25886d295b3bc..7eb632ba69882 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -18,7 +18,6 @@ #![doc(test(attr(deny(warnings))))] #![doc(rust_logo)] #![feature(rustdoc_internals)] -#![feature(exitcode_exit_method)] #![feature(file_buffered)] #![feature(internal_output_capture)] #![feature(io_const_error)] @@ -31,16 +30,17 @@ #![warn(rustdoc::unescaped_backticks)] #![warn(unreachable_pub)] +pub use std::process::ExitCode; // used by rustc-generated test harness + pub use cli::TestOpts; pub use self::ColorConfig::*; pub use self::bench::{Bencher, black_box}; pub use self::console::run_tests_console; pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic}; -pub use self::types::TestName::*; pub use self::types::*; -// Module to be used by rustc to compile tests in libtest +// Make some items publicly available for our own tests. pub mod test { pub use crate::bench::Bencher; pub use crate::cli::{TestOpts, parse_opts}; @@ -48,18 +48,13 @@ pub mod test { pub use crate::options::{Options, RunIgnored, RunStrategy, ShouldPanic}; pub use crate::test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk}; pub use crate::time::{TestExecTime, TestTimeOptions}; - pub use crate::types::{ - DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc, - TestDescAndFn, TestId, TestList, TestListOrder, TestName, TestType, - }; - pub use crate::{assert_test_result, filter_tests, run_test, test_main, test_main_env_args}; } use std::collections::VecDeque; use std::io::prelude::Write; use std::mem::ManuallyDrop; use std::panic::{self, AssertUnwindSafe, PanicHookInfo, catch_unwind}; -use std::process::{self, Command, ExitCode, Termination}; +use std::process::{self, Command, Termination}; use std::sync::mpsc::{Sender, channel}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -170,34 +165,28 @@ fn test_main_inner(args: &[String], tests: TestList<'_>, options: Option ExitCode { // This is supposed to be reasonably fast even in Miri. In particular, when invoked via `--exact // test`, we want the entire invocation to be `O(log n)` in the number of tests: never iterate // the entire test list (as that list could be big)! let args = env::args().collect::>(); // Tests are sorted by name at compile time by mk_tests_slice. let tests = TestList::new(tests, TestListOrder::Sorted); - let exit = test_main_inner(&args, tests, None); - // We do *not* want to exit here on success, that breaks coverage tracking on Windows. - if exit != std::process::ExitCode::SUCCESS { - exit.exit_process(); - } + test_main_inner(&args, tests, None) } -/// A variant that takes the arguments from the command line. Exits the process if there -/// was an error, returns on success. +/// A variant that takes the arguments from the command line. /// /// Runs tests in panic=abort mode, which involves spawning subprocesses for /// tests. If we are invoked as subprocess, this function does not return. /// /// This is the entry point for the main function generated by `rustc --test` /// when panic=abort. -pub fn test_main_env_args_abort(tests: &[&TestDescAndFn]) { +pub fn test_main_env_args_abort(tests: &[&TestDescAndFn]) -> ExitCode { // If we're being run in SpawnedSecondary mode, run the test here. run_test // will then exit the process. if let Ok(name) = env::var(SECONDARY_TEST_INVOKER_VAR) { @@ -246,10 +235,7 @@ pub fn test_main_env_args_abort(tests: &[&TestDescAndFn]) { let args = env::args().collect::>(); // Tests are sorted by name at compile time by mk_tests_slice. let tests = TestList::new(tests, TestListOrder::Sorted); - let exit = test_main_inner(&args, tests, Some(Options::new().panic_abort(true))); - if exit != std::process::ExitCode::SUCCESS { - exit.exit_process(); - } + test_main_inner(&args, tests, Some(Options::new().panic_abort(true))) } /// Public API used by rustdoc to display the `total` and `compilation` times in the expected diff --git a/src/tools/clippy/clippy_lints/src/items_after_test_module.rs b/src/tools/clippy/clippy_lints/src/items_after_test_module.rs index 9cd71c62eb32a..dac7a24bf2a8d 100644 --- a/src/tools/clippy/clippy_lints/src/items_after_test_module.rs +++ b/src/tools/clippy/clippy_lints/src/items_after_test_module.rs @@ -65,9 +65,9 @@ impl LateLintPass<'_> for ItemsAfterTestModule { let after: Vec<_> = items .filter(|item| { - // Ignore the generated test main function - if let ItemKind::Fn { ident, .. } = item.kind - && ident.name == sym::main + // Ignore the generated test main function and `extern crate test` + if (matches!(item.kind, ItemKind::Fn { ident, .. } if ident.name == sym::main) + || matches!(item.kind, ItemKind::ExternCrate(None, ident) if ident.name == sym::test)) && item.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::TestHarness) { false diff --git a/tests/assembly-llvm/closure-inherit-target-feature.rs b/tests/assembly-llvm/closure-inherit-target-feature.rs index c3753a534a027..737e4ed655218 100644 --- a/tests/assembly-llvm/closure-inherit-target-feature.rs +++ b/tests/assembly-llvm/closure-inherit-target-feature.rs @@ -8,16 +8,14 @@ use std::arch::x86_64::{__m128, _mm_blend_ps}; -// Use an explicit return pointer to prevent tail call optimization. #[no_mangle] pub unsafe fn sse41_blend_nofeature(x: __m128, y: __m128, ret: *mut __m128) { let f = { // check that _mm_blend_ps is not being inlined into the closure // CHECK-LABEL: {{sse41_blend_nofeature:}} // CHECK-NOT: blendps - // CHECK: {{call .*_mm_blend_ps.*}} + // CHECK: {{(call|jmp) .*_mm_blend_ps.*}} // CHECK-NOT: blendps - // CHECK: ret #[inline(never)] |x, y, ret: *mut __m128| unsafe { *ret = _mm_blend_ps(x, y, 0b0101) } }; diff --git a/tests/pretty/tests-are-sorted.pp b/tests/pretty/tests-are-sorted.pp index 0002189b48c04..e3edb7e22a0b5 100644 --- a/tests/pretty/tests-are-sorted.pp +++ b/tests/pretty/tests-are-sorted.pp @@ -80,10 +80,10 @@ test::assert_test_result(a_test())), }; fn a_test() {} +extern crate test; #[rustc_main] #[coverage(off)] #[doc(hidden)] -pub fn main() -> () { - extern crate test; +pub fn main() -> test::ExitCode { test::test_main_env_args(&[&a_test, &m_test, &z_test]) } diff --git a/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.legacy.stderr b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.legacy.stderr new file mode 100644 index 0000000000000..8cf41b45af61d --- /dev/null +++ b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.legacy.stderr @@ -0,0 +1,22 @@ +error[E0505]: cannot move out of `b` because it is borrowed + --> $DIR/drop-liveness-invariance-issue-160670.rs:38:10 + | +LL | let b = Box::new(0u8); + | - binding `b` declared here +LL | let d; +LL | d = mk(&*b); + | --- borrow of `*b` occurs here +LL | drop(b); + | ^ move out of `b` occurs here +LL | } + | - borrow might be used here, when `d` is dropped and runs the `Drop` code for type `D` + | +help: consider cloning the value if the performance cost is acceptable + | +LL - d = mk(&*b); +LL + d = mk(&b.clone()); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0505`. diff --git a/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.nll.stderr b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.nll.stderr new file mode 100644 index 0000000000000..8cf41b45af61d --- /dev/null +++ b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.nll.stderr @@ -0,0 +1,22 @@ +error[E0505]: cannot move out of `b` because it is borrowed + --> $DIR/drop-liveness-invariance-issue-160670.rs:38:10 + | +LL | let b = Box::new(0u8); + | - binding `b` declared here +LL | let d; +LL | d = mk(&*b); + | --- borrow of `*b` occurs here +LL | drop(b); + | ^ move out of `b` occurs here +LL | } + | - borrow might be used here, when `d` is dropped and runs the `Drop` code for type `D` + | +help: consider cloning the value if the performance cost is acceptable + | +LL - d = mk(&*b); +LL + d = mk(&b.clone()); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0505`. diff --git a/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.polonius.stderr b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.polonius.stderr new file mode 100644 index 0000000000000..8cf41b45af61d --- /dev/null +++ b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.polonius.stderr @@ -0,0 +1,22 @@ +error[E0505]: cannot move out of `b` because it is borrowed + --> $DIR/drop-liveness-invariance-issue-160670.rs:38:10 + | +LL | let b = Box::new(0u8); + | - binding `b` declared here +LL | let d; +LL | d = mk(&*b); + | --- borrow of `*b` occurs here +LL | drop(b); + | ^ move out of `b` occurs here +LL | } + | - borrow might be used here, when `d` is dropped and runs the `Drop` code for type `D` + | +help: consider cloning the value if the performance cost is acceptable + | +LL - d = mk(&*b); +LL + d = mk(&b.clone()); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0505`. diff --git a/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.rs b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.rs new file mode 100644 index 0000000000000..b1f53190b2c74 --- /dev/null +++ b/tests/ui/borrowck/alias-liveness/drop-liveness-invariance-issue-160670.rs @@ -0,0 +1,39 @@ +// From https://github.com/rust-lang/rust/issues/160670 This issue was +// discovered when developing Polonius alpha. A live local (the one holding the +// struct `D`) had its type be drop-live, but only partially. This had not +// previously triggered any issues because it did not affect region liveness, +// but it did affect Polonius' region variance computations, since the outer `D` +// nesting was removed to obtain `fn(&'a T)`, which unlike the associated type +// isn't invariant. +// +// The split declaration/assignment on lines 39--40 is load bearing; without +// them the bug does not appear due to a `FakeRead` being introduced and +// ensuring liveness. + +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: nll polonius legacy +//@ [nll] compile-flags: -Z polonius=off +//@ [polonius] compile-flags: -Z polonius=next +//@ [legacy] compile-flags: -Z polonius=legacy + +struct D(T::Arg); + +trait HasArg { + type Arg; +} +impl<'a, T> HasArg for fn(&'a T) { + type Arg = &'a T; +} +impl Drop for D { + fn drop(&mut self) {} +} +fn mk<'a, T>(r: &'a T) -> D { + D(r) +} + +fn main() { + let b = Box::new(0u8); + let d; + d = mk(&*b); + drop(b); //~ ERROR cannot move out of `b` because it is borrowed +}