diff --git a/.mailmap b/.mailmap index 122751a6be8a1..b6f4112392db7 100644 --- a/.mailmap +++ b/.mailmap @@ -31,6 +31,8 @@ Alexis Beingessner Alfie John Alfie John Alona Enraght-Moony Alona Enraght-Moony +Amanda Stjerna +Amanda Stjerna Amos Onn Ana-Maria Mihalache Anatoly Ikorsky diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 47a387e25e3a4..6a911b23462cb 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -470,7 +470,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } - ty.print(printer).unwrap().into_buffer() + ty.print(&mut printer).unwrap(); + printer.into_buffer() } /// Returns the name of the provided `Ty` (that must be a reference)'s region with a @@ -492,7 +493,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { bug!("ty for annotation of borrow region is not a reference"); }; - region.print(printer).unwrap().into_buffer() + region.print(&mut printer).unwrap(); + printer.into_buffer() } } diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 99424518ad46f..6716888290dc1 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -107,10 +107,10 @@ impl std::fmt::Display for ImmTy<'_, Prov> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// Helper function for printing a scalar to a FmtPrinter fn p<'a, 'tcx, Prov: Provenance>( - cx: FmtPrinter<'a, 'tcx>, + cx: &mut FmtPrinter<'a, 'tcx>, s: Scalar, ty: Ty<'tcx>, - ) -> Result, std::fmt::Error> { + ) -> Result<(), std::fmt::Error> { match s { Scalar::Int(int) => cx.pretty_print_const_scalar_int(int, ty, true), Scalar::Ptr(ptr, _sz) => { @@ -125,8 +125,9 @@ impl std::fmt::Display for ImmTy<'_, Prov> { match self.imm { Immediate::Scalar(s) => { if let Some(ty) = tcx.lift(self.layout.ty) { - let cx = FmtPrinter::new(tcx, Namespace::ValueNS); - f.write_str(&p(cx, s, ty)?.into_buffer())?; + let s = + FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| p(cx, s, ty))?; + f.write_str(&s)?; return Ok(()); } write!(f, "{:x}: {}", s, self.layout.ty) diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index 8c7c360acbfdf..a82b65b19a882 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -18,11 +18,11 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { self.tcx } - fn print_region(self, _region: ty::Region<'_>) -> Result { - Ok(self) + fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { + Ok(()) } - fn print_type(mut self, ty: Ty<'tcx>) -> Result { + fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { match *ty.kind() { // Types without identity. ty::Bool @@ -43,7 +43,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { // Placeholders (all printed as `_` to uniformize them). ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => { write!(self, "_")?; - Ok(self) + Ok(()) } // Types with identity (print the module path). @@ -60,44 +60,44 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { } } - fn print_const(self, ct: ty::Const<'tcx>) -> Result { + fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> { self.pretty_print_const(ct, false) } fn print_dyn_existential( - self, + &mut self, predicates: &'tcx ty::List>, - ) -> Result { + ) -> Result<(), PrintError> { self.pretty_print_dyn_existential(predicates) } - fn path_crate(mut self, cnum: CrateNum) -> Result { + fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.path.push_str(self.tcx.crate_name(cnum).as_str()); - Ok(self) + Ok(()) } fn path_qualified( - self, + &mut self, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { self.pretty_path_qualified(self_ty, trait_ref) } fn path_append_impl( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { self.pretty_path_append_impl( - |mut cx| { - cx = print_prefix(cx)?; + |cx| { + print_prefix(cx)?; cx.path.push_str("::"); - Ok(cx) + Ok(()) }, self_ty, trait_ref, @@ -105,29 +105,29 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { } fn path_append( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; write!(self.path, "::{}", disambiguated_data.data).unwrap(); - Ok(self) + Ok(()) } fn path_generic_args( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, args: &[GenericArg<'tcx>], - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; let args = args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_))); if args.clone().next().is_some() { self.generic_delimiters(|cx| cx.comma_sep(args)) } else { - Ok(self) + Ok(()) } } } @@ -136,31 +136,31 @@ impl<'tcx> PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> { fn should_print_region(&self, _region: ty::Region<'_>) -> bool { false } - fn comma_sep(mut self, mut elems: impl Iterator) -> Result + fn comma_sep(&mut self, mut elems: impl Iterator) -> Result<(), PrintError> where T: Print<'tcx, Self>, { if let Some(first) = elems.next() { - self = first.print(self)?; + first.print(self)?; for elem in elems { self.path.push_str(", "); - self = elem.print(self)?; + elem.print(self)?; } } - Ok(self) + Ok(()) } fn generic_delimiters( - mut self, - f: impl FnOnce(Self) -> Result, - ) -> Result { + &mut self, + f: impl FnOnce(&mut Self) -> Result<(), PrintError>, + ) -> Result<(), PrintError> { write!(self, "<")?; - self = f(self)?; + f(self)?; write!(self, ">")?; - Ok(self) + Ok(()) } fn should_print_verbose(&self) -> bool { @@ -177,5 +177,7 @@ impl Write for AbsolutePathPrinter<'_> { } pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String { - AbsolutePathPrinter { tcx, path: String::new() }.print_type(ty).unwrap().path + let mut printer = AbsolutePathPrinter { tcx, path: String::new() }; + printer.print_type(ty).unwrap(); + printer.path } diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 110ec052b35d4..e0ccf04ab6332 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -12,6 +12,7 @@ use rustc_hir::pat_util::EnumerateAndAdjustIterator; use rustc_hir::{HirId, Pat, PatKind}; use rustc_infer::infer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; +use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::{self, Adt, BindingMode, Ty, TypeVisitableExt}; use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; use rustc_span::edit_distance::find_best_match_for_name; @@ -2164,7 +2165,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { len: ty::Const<'tcx>, min_len: u64, ) -> (Option>, Ty<'tcx>) { - let guar = if let Some(len) = len.try_eval_target_usize(self.tcx, self.param_env) { + let len = match len.eval(self.tcx, self.param_env, None) { + Ok(val) => val + .try_to_scalar() + .and_then(|scalar| scalar.try_to_int().ok()) + .and_then(|int| int.try_to_target_usize(self.tcx).ok()), + Err(ErrorHandled::Reported(..)) => { + let guar = self.error_scrutinee_unfixed_length(span); + return (Some(Ty::new_error(self.tcx, guar)), arr_ty); + } + Err(ErrorHandled::TooGeneric(..)) => None, + }; + + let guar = if let Some(len) = len { // Now we know the length... if slice.is_none() { // ...and since there is no variable-length pattern, diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 97ab3d0b7517d..ba118f8110f31 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -588,60 +588,60 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { self.tcx } - fn print_region(self, _region: ty::Region<'_>) -> Result { + fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { Err(fmt::Error) } - fn print_type(self, _ty: Ty<'tcx>) -> Result { + fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> { Err(fmt::Error) } fn print_dyn_existential( - self, + &mut self, _predicates: &'tcx ty::List>, - ) -> Result { + ) -> Result<(), PrintError> { Err(fmt::Error) } - fn print_const(self, _ct: ty::Const<'tcx>) -> Result { + fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> { Err(fmt::Error) } - fn path_crate(mut self, cnum: CrateNum) -> Result { + fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.segments = vec![self.tcx.crate_name(cnum).to_string()]; - Ok(self) + Ok(()) } fn path_qualified( - self, + &mut self, _self_ty: Ty<'tcx>, _trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { Err(fmt::Error) } fn path_append_impl( - self, - _print_prefix: impl FnOnce(Self) -> Result, + &mut self, + _print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _disambiguated_data: &DisambiguatedDefPathData, _self_ty: Ty<'tcx>, _trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { Err(fmt::Error) } fn path_append( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; self.segments.push(disambiguated_data.to_string()); - Ok(self) + Ok(()) } fn path_generic_args( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _args: &[GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { print_prefix(self) } } @@ -652,9 +652,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // let _ = [{struct Foo; Foo}, {struct Foo; Foo}]; if did1.krate != did2.krate { let abs_path = |def_id| { - AbsolutePathPrinter { tcx: self.tcx, segments: vec![] } - .print_def_path(def_id, &[]) - .map(|p| p.segments) + let mut printer = AbsolutePathPrinter { tcx: self.tcx, segments: vec![] }; + printer.print_def_path(def_id, &[]).map(|_| printer.segments) }; // We compare strings because DefPath can be different @@ -1071,7 +1070,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let get_lifetimes = |sig| { use rustc_hir::def::Namespace; - let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS) + let (sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS) .name_all_regions(sig) .unwrap(); let lts: Vec = reg.into_values().map(|kind| kind.to_string()).collect(); diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index 7bc414ff52218..4beb51da72ced 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -200,12 +200,15 @@ fn ty_to_string<'tcx>( ty: Ty<'tcx>, called_method_def_id: Option, ) -> String { - let printer = fmt_printer(infcx, Namespace::TypeNS); + let mut printer = fmt_printer(infcx, Namespace::TypeNS); let ty = infcx.resolve_vars_if_possible(ty); match (ty.kind(), called_method_def_id) { // We don't want the regular output for `fn`s because it includes its path in // invalid pseudo-syntax, we want the `fn`-pointer output instead. - (ty::FnDef(..), _) => ty.fn_sig(infcx.tcx).print(printer).unwrap().into_buffer(), + (ty::FnDef(..), _) => { + ty.fn_sig(infcx.tcx).print(&mut printer).unwrap(); + printer.into_buffer() + } (_, Some(def_id)) if ty.is_ty_or_numeric_infer() && infcx.tcx.get_diagnostic_item(sym::iterator_collect_fn) == Some(def_id) => @@ -218,7 +221,10 @@ fn ty_to_string<'tcx>( // // We do have to hide the `extern "rust-call"` ABI in that case though, // which is too much of a bother for now. - _ => ty.print(printer).unwrap().into_buffer(), + _ => { + ty.print(&mut printer).unwrap(); + printer.into_buffer() + } } } @@ -285,8 +291,9 @@ impl<'tcx> InferCtxt<'tcx> { if let Some(highlight) = highlight { printer.region_highlight_mode = highlight; } + ty.print(&mut printer).unwrap(); InferenceDiagnosticsData { - name: ty.print(printer).unwrap().into_buffer(), + name: printer.into_buffer(), span: None, kind: UnderspecifiedArgKind::Type { prefix: ty.prefix_string(self.tcx) }, parent: None, @@ -312,8 +319,9 @@ impl<'tcx> InferCtxt<'tcx> { if let Some(highlight) = highlight { printer.region_highlight_mode = highlight; } + ct.print(&mut printer).unwrap(); InferenceDiagnosticsData { - name: ct.print(printer).unwrap().into_buffer(), + name: printer.into_buffer(), span: Some(origin.span), kind: UnderspecifiedArgKind::Const { is_parameter: false }, parent: None, @@ -329,8 +337,9 @@ impl<'tcx> InferCtxt<'tcx> { if let Some(highlight) = highlight { printer.region_highlight_mode = highlight; } + ct.print(&mut printer).unwrap(); InferenceDiagnosticsData { - name: ct.print(printer).unwrap().into_buffer(), + name: printer.into_buffer(), span: None, kind: UnderspecifiedArgKind::Const { is_parameter: false }, parent: None, @@ -487,7 +496,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { { "Vec<_>".to_string() } else { - fmt_printer(self, Namespace::TypeNS) + let mut printer = fmt_printer(self, Namespace::TypeNS); + printer .comma_sep(generic_args.iter().copied().map(|arg| { if arg.is_suggestable(self.tcx, true) { return arg; @@ -512,8 +522,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { .into(), } })) - .unwrap() - .into_buffer() + .unwrap(); + printer.into_buffer() }; if !have_turbofish { @@ -525,8 +535,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } } InferSourceKind::FullyQualifiedMethodCall { receiver, successor, args, def_id } => { - let printer = fmt_printer(self, Namespace::ValueNS); - let def_path = printer.print_def_path(def_id, args).unwrap().into_buffer(); + let mut printer = fmt_printer(self, Namespace::ValueNS); + printer.print_def_path(def_id, args).unwrap(); + let def_path = printer.into_buffer(); // We only care about whether we have to add `&` or `&mut ` for now. // This is the case if the last adjustment is a borrow and the diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs index d6a3bc32cc937..c38e5b8cd09e5 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs @@ -49,8 +49,8 @@ where let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS); printer.region_highlight_mode = self.highlight; - let s = self.value.print(printer)?.into_buffer(); - f.write_str(&s) + self.value.print(&mut printer)?; + f.write_str(&printer.into_buffer()) } } diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index faea8bc98aa2d..00289f9bfb411 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -763,9 +763,9 @@ fn foo(&self) -> Self::T { String::new() } } pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String { - FmtPrinter::new(self.tcx, hir::def::Namespace::TypeNS) - .path_generic_args(Ok, args) - .expect("could not write to `String`.") - .into_buffer() + FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |cx| { + cx.path_generic_args(|_| Ok(()), args) + }) + .expect("could not write to `String`.") } } diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 1f08db3086076..5b7ba03d9adfc 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -1210,35 +1210,35 @@ impl<'tcx> LateContext<'tcx> { self.tcx } - fn print_region(self, _region: ty::Region<'_>) -> Result { - Ok(self) + fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { + Ok(()) } - fn print_type(self, _ty: Ty<'tcx>) -> Result { - Ok(self) + fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> { + Ok(()) } fn print_dyn_existential( - self, + &mut self, _predicates: &'tcx ty::List>, - ) -> Result { - Ok(self) + ) -> Result<(), PrintError> { + Ok(()) } - fn print_const(self, _ct: ty::Const<'tcx>) -> Result { - Ok(self) + fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> { + Ok(()) } - fn path_crate(mut self, cnum: CrateNum) -> Result { + fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.path = vec![self.tcx.crate_name(cnum)]; - Ok(self) + Ok(()) } fn path_qualified( - mut self, + &mut self, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { if trait_ref.is_none() { if let ty::Adt(def, args) = self_ty.kind() { return self.print_def_path(def.did(), args); @@ -1251,21 +1251,21 @@ impl<'tcx> LateContext<'tcx> { Some(trait_ref) => Symbol::intern(&format!("{trait_ref:?}")), None => Symbol::intern(&format!("<{self_ty}>")), }]; - Ok(self) + Ok(()) }) } fn path_append_impl( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { - let mut path = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; // This shouldn't ever be needed, but just in case: - path.path.push(match trait_ref { + self.path.push(match trait_ref { Some(trait_ref) => { with_no_trimmed_paths!(Symbol::intern(&format!( "", @@ -1278,38 +1278,37 @@ impl<'tcx> LateContext<'tcx> { } }); - Ok(path) + Ok(()) } fn path_append( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, - ) -> Result { - let mut path = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs. if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data { - return Ok(path); + return Ok(()); } - path.path.push(Symbol::intern(&disambiguated_data.data.to_string())); - Ok(path) + self.path.push(Symbol::intern(&disambiguated_data.data.to_string())); + Ok(()) } fn path_generic_args( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _args: &[GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { print_prefix(self) } } - AbsolutePathPrinter { tcx: self.tcx, path: vec![] } - .print_def_path(def_id, &[]) - .unwrap() - .path + let mut printer = AbsolutePathPrinter { tcx: self.tcx, path: vec![] }; + printer.print_def_path(def_id, &[]).unwrap(); + printer.path } /// Returns the associated type `name` for `self_ty` as an implementation of `trait_id`. diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index dee25df53bd2b..12057f5e1cb66 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -998,9 +998,9 @@ impl<'tcx> Debug for Rvalue<'tcx> { ty::tls::with(|tcx| { let variant_def = &tcx.adt_def(adt_did).variant(variant); let args = tcx.lift(args).expect("could not lift for printing"); - let name = FmtPrinter::new(tcx, Namespace::ValueNS) - .print_def_path(variant_def.def_id, args)? - .into_buffer(); + let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| { + cx.print_def_path(variant_def.def_id, args) + })?; match variant_def.ctor_kind() { Some(CtorKind::Const) => fmt.write_str(&name), @@ -1740,7 +1740,7 @@ fn pretty_print_const_value_tcx<'tcx>( let args = tcx.lift(args).unwrap(); let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); cx.print_alloc_ids = true; - let cx = cx.print_value_path(variant_def.def_id, args)?; + cx.print_value_path(variant_def.def_id, args)?; fmt.write_str(&cx.into_buffer())?; match variant_def.ctor_kind() { @@ -1775,14 +1775,14 @@ fn pretty_print_const_value_tcx<'tcx>( let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); cx.print_alloc_ids = true; let ty = tcx.lift(ty).unwrap(); - cx = cx.pretty_print_const_scalar(scalar, ty)?; + cx.pretty_print_const_scalar(scalar, ty)?; fmt.write_str(&cx.into_buffer())?; return Ok(()); } (ConstValue::ZeroSized, ty::FnDef(d, s)) => { let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); cx.print_alloc_ids = true; - let cx = cx.print_value_path(*d, s)?; + cx.print_value_path(*d, s)?; fmt.write_str(&cx.into_buffer())?; return Ok(()); } diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 8b4375f0270b5..184a70ed4cb8c 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -315,26 +315,25 @@ impl<'tcx> Ty<'tcx> { impl<'tcx> TyCtxt<'tcx> { pub fn ty_string_with_limit(self, ty: Ty<'tcx>, length_limit: usize) -> String { let mut type_limit = 50; - let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS) - .pretty_print_type(ty) - .expect("could not write to `String`") - .into_buffer(); + let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| { + cx.pretty_print_type(ty) + }) + .expect("could not write to `String`"); if regular.len() <= length_limit { return regular; } let mut short; loop { // Look for the longest properly trimmed path that still fits in length_limit. - short = with_forced_trimmed_paths!( - FmtPrinter::new_with_limit( + short = with_forced_trimmed_paths!({ + let mut cx = FmtPrinter::new_with_limit( self, hir::def::Namespace::TypeNS, rustc_session::Limit(type_limit), - ) - .pretty_print_type(ty) - .expect("could not write to `String`") - .into_buffer() - ); + ); + cx.pretty_print_type(ty).expect("could not write to `String`"); + cx.into_buffer() + }); if short.len() <= length_limit || type_limit == 0 { break; } @@ -344,10 +343,10 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option) { - let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS) - .pretty_print_type(ty) - .expect("could not write to `String`") - .into_buffer(); + let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| { + cx.pretty_print_type(ty) + }) + .expect("could not write to `String`"); if !self.sess.opts.unstable_opts.write_long_types_to_disk { return (regular, None); diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index a7d6e97c941f9..cebefbccc11d1 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -298,9 +298,9 @@ fn fmt_instance( ty::tls::with(|tcx| { let args = tcx.lift(instance.args).expect("could not lift for printing"); - let s = FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length) - .print_def_path(instance.def_id(), args)? - .into_buffer(); + let mut cx = FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length); + cx.print_def_path(instance.def_id(), args)?; + let s = cx.into_buffer(); f.write_str(&s) })?; diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 164e4232e4c61..80af8a9255398 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -15,7 +15,7 @@ pub type PrintError = std::fmt::Error; // FIXME(eddyb) false positive, the lifetime parameters are used with `P: Printer<...>`. #[allow(unused_lifetimes)] pub trait Print<'tcx, P> { - fn print(&self, cx: P) -> Result; + fn print(&self, cx: &mut P) -> Result<(), PrintError>; } /// Interface for outputting user-facing "type-system entities" @@ -31,70 +31,70 @@ pub trait Printer<'tcx>: Sized { fn tcx<'a>(&'a self) -> TyCtxt<'tcx>; fn print_def_path( - self, + &mut self, def_id: DefId, args: &'tcx [GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { self.default_print_def_path(def_id, args) } fn print_impl_path( - self, + &mut self, impl_def_id: DefId, args: &'tcx [GenericArg<'tcx>], self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { self.default_print_impl_path(impl_def_id, args, self_ty, trait_ref) } - fn print_region(self, region: ty::Region<'tcx>) -> Result; + fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError>; - fn print_type(self, ty: Ty<'tcx>) -> Result; + fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError>; fn print_dyn_existential( - self, + &mut self, predicates: &'tcx ty::List>, - ) -> Result; + ) -> Result<(), PrintError>; - fn print_const(self, ct: ty::Const<'tcx>) -> Result; + fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError>; - fn path_crate(self, cnum: CrateNum) -> Result; + fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError>; fn path_qualified( - self, + &mut self, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result; + ) -> Result<(), PrintError>; fn path_append_impl( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result; + ) -> Result<(), PrintError>; fn path_append( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, - ) -> Result; + ) -> Result<(), PrintError>; fn path_generic_args( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, args: &[GenericArg<'tcx>], - ) -> Result; + ) -> Result<(), PrintError>; // Defaults (should not be overridden): #[instrument(skip(self), level = "debug")] fn default_print_def_path( - self, + &mut self, def_id: DefId, args: &'tcx [GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { let key = self.tcx().def_key(def_id); debug!(?key); @@ -161,7 +161,7 @@ pub trait Printer<'tcx>: Sized { } self.path_append( - |cx: Self| { + |cx: &mut Self| { if trait_qualify_parent { let trait_ref = ty::TraitRef::new( cx.tcx(), @@ -180,12 +180,12 @@ pub trait Printer<'tcx>: Sized { } fn default_print_impl_path( - self, + &mut self, impl_def_id: DefId, _args: &'tcx [GenericArg<'tcx>], self_ty: Ty<'tcx>, impl_trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { debug!( "default_print_impl_path: impl_def_id={:?}, self_ty={}, impl_trait_ref={:?}", impl_def_id, self_ty, impl_trait_ref @@ -286,25 +286,25 @@ pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option { } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Region<'tcx> { - fn print(&self, cx: P) -> Result { + fn print(&self, cx: &mut P) -> Result<(), PrintError> { cx.print_region(*self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for Ty<'tcx> { - fn print(&self, cx: P) -> Result { + fn print(&self, cx: &mut P) -> Result<(), PrintError> { cx.print_type(*self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for &'tcx ty::List> { - fn print(&self, cx: P) -> Result { + fn print(&self, cx: &mut P) -> Result<(), PrintError> { cx.print_dyn_existential(self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Const<'tcx> { - fn print(&self, cx: P) -> Result { + fn print(&self, cx: &mut P) -> Result<(), PrintError> { cx.print_const(*self) } } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 38b3096f85182..316370977a426 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -42,10 +42,10 @@ macro_rules! p { write!(scoped_cx!(), $($data),+)? }; (@print($x:expr)) => { - scoped_cx!() = $x.print(scoped_cx!())? + $x.print(scoped_cx!())? }; (@$method:ident($($arg:expr),*)) => { - scoped_cx!() = scoped_cx!().$method($($arg),*)? + scoped_cx!().$method($($arg),*)? }; ($($elem:tt $(($($args:tt)*))?),+) => {{ $(p!(@ $elem $(($($args)*))?);)+ @@ -209,25 +209,25 @@ impl<'tcx> RegionHighlightMode<'tcx> { pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { /// Like `print_def_path` but for value paths. fn print_value_path( - self, + &mut self, def_id: DefId, args: &'tcx [GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { self.print_def_path(def_id, args) } - fn in_binder(self, value: &ty::Binder<'tcx, T>) -> Result + fn in_binder(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError> where T: Print<'tcx, Self> + TypeFoldable>, { value.as_ref().skip_binder().print(self) } - fn wrap_binder Result>( - self, + fn wrap_binder Result<(), fmt::Error>>( + &mut self, value: &ty::Binder<'tcx, T>, f: F, - ) -> Result + ) -> Result<(), PrintError> where T: Print<'tcx, Self> + TypeFoldable>, { @@ -235,40 +235,40 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } /// Prints comma-separated elements. - fn comma_sep(mut self, mut elems: impl Iterator) -> Result + fn comma_sep(&mut self, mut elems: impl Iterator) -> Result<(), PrintError> where T: Print<'tcx, Self>, { if let Some(first) = elems.next() { - self = first.print(self)?; + first.print(self)?; for elem in elems { self.write_str(", ")?; - self = elem.print(self)?; + elem.print(self)?; } } - Ok(self) + Ok(()) } /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument fn typed_value( - mut self, - f: impl FnOnce(Self) -> Result, - t: impl FnOnce(Self) -> Result, + &mut self, + f: impl FnOnce(&mut Self) -> Result<(), PrintError>, + t: impl FnOnce(&mut Self) -> Result<(), PrintError>, conversion: &str, - ) -> Result { + ) -> Result<(), PrintError> { self.write_str("{")?; - self = f(self)?; + f(self)?; self.write_str(conversion)?; - self = t(self)?; + t(self)?; self.write_str("}")?; - Ok(self) + Ok(()) } /// Prints `<...>` around what `f` prints. fn generic_delimiters( - self, - f: impl FnOnce(Self) -> Result, - ) -> Result; + &mut self, + f: impl FnOnce(&mut Self) -> Result<(), PrintError>, + ) -> Result<(), PrintError>; /// Returns `true` if the region should be printed in /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`. @@ -282,9 +282,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { /// If possible, this returns a global path resolving to `def_id` that is visible /// from at least one local module, and returns `true`. If the crate defining `def_id` is /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`. - fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), PrintError> { + fn try_print_visible_def_path(&mut self, def_id: DefId) -> Result { if NO_VISIBLE_PATH.with(|flag| flag.get()) { - return Ok((self, false)); + return Ok(false); } let mut callers = Vec::new(); @@ -296,7 +296,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // For enum variants, if they have an unique name, then we only print the name, otherwise we // print the enum name and the variant name. Otherwise, we do not print anything and let the // caller use the `print_def_path` fallback. - fn force_print_trimmed_def_path(mut self, def_id: DefId) -> Result<(Self, bool), PrintError> { + fn force_print_trimmed_def_path(&mut self, def_id: DefId) -> Result { let key = self.tcx().def_key(def_id); let visible_parent_map = self.tcx().visible_parent_map(()); let kind = self.tcx().def_kind(def_id); @@ -324,7 +324,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { { // If `Assoc` is unique, we don't want to talk about `Trait::Assoc`. self.write_str(get_local_name(&self, *symbol, def_id, key).as_str())?; - return Ok((self, true)); + return Ok(true); } if let Some(symbol) = key.get_opt_name() { if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = kind @@ -357,36 +357,35 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { { } else { // If not covered above, like for example items out of `impl` blocks, fallback. - return Ok((self, false)); + return Ok(false); } self.write_str(get_local_name(&self, symbol, def_id, key).as_str())?; - return Ok((self, true)); + return Ok(true); } - Ok((self, false)) + Ok(false) } /// Try to see if this path can be trimmed to a unique symbol name. - fn try_print_trimmed_def_path(mut self, def_id: DefId) -> Result<(Self, bool), PrintError> { + fn try_print_trimmed_def_path(&mut self, def_id: DefId) -> Result { if FORCE_TRIMMED_PATH.with(|flag| flag.get()) { - let (s, trimmed) = self.force_print_trimmed_def_path(def_id)?; + let trimmed = self.force_print_trimmed_def_path(def_id)?; if trimmed { - return Ok((s, true)); + return Ok(true); } - self = s; } if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never) || NO_TRIMMED_PATH.with(|flag| flag.get()) || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) { - return Ok((self, false)); + return Ok(false); } match self.tcx().trimmed_def_paths(()).get(&def_id) { - None => Ok((self, false)), + None => Ok(false), Some(symbol) => { write!(self, "{}", Ident::with_dummy_span(*symbol))?; - Ok((self, true)) + Ok(true) } } } @@ -405,10 +404,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { /// This method returns false if we can't print the visible path, so /// `print_def_path` can fall back on the item's real definition path. fn try_print_visible_def_path_recur( - mut self, + &mut self, def_id: DefId, callers: &mut Vec, - ) -> Result<(Self, bool), PrintError> { + ) -> Result { define_scoped_cx!(self); debug!("try_print_visible_def_path: def_id={:?}", def_id); @@ -417,7 +416,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // path to the crate followed by the path to the item within the crate. if let Some(cnum) = def_id.as_crate_root() { if cnum == LOCAL_CRATE { - return Ok((self.path_crate(cnum)?, true)); + self.path_crate(cnum)?; + return Ok(true); } // In local mode, when we encounter a crate other than @@ -440,7 +440,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // or avoid ending up with `ExternCrateSource::Extern`, // for the injected `std`/`core`. if span.is_dummy() { - return Ok((self.path_crate(cnum)?, true)); + self.path_crate(cnum)?; + return Ok(true); } // Disable `try_print_trimmed_def_path` behavior within @@ -448,23 +449,25 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // in cases where the `extern crate foo` has non-trivial // parents, e.g. it's nested in `impl foo::Trait for Bar` // (see also issues #55779 and #87932). - self = with_no_visible_paths!(self.print_def_path(def_id, &[])?); + with_no_visible_paths!(self.print_def_path(def_id, &[])?); - return Ok((self, true)); + return Ok(true); } (ExternCrateSource::Path, LOCAL_CRATE) => { - return Ok((self.path_crate(cnum)?, true)); + self.path_crate(cnum)?; + return Ok(true); } _ => {} }, None => { - return Ok((self.path_crate(cnum)?, true)); + self.path_crate(cnum)?; + return Ok(true); } } } if def_id.is_local() { - return Ok((self, false)); + return Ok(false); } let visible_parent_map = self.tcx().visible_parent_map(()); @@ -485,7 +488,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else { - return Ok((self, false)); + return Ok(false); }; let actual_parent = self.tcx().opt_parent(def_id); @@ -548,7 +551,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { *name = new_name; } else { // There is no name that is public and isn't `_`, so bail. - return Ok((self, false)); + return Ok(false); } } // Re-exported `extern crate` (#43189). @@ -560,7 +563,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { debug!("try_print_visible_def_path: data={:?}", data); if callers.contains(&visible_parent) { - return Ok((self, false)); + return Ok(false); } callers.push(visible_parent); // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid @@ -568,19 +571,19 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // To support printers that do not implement `PrettyPrinter`, a `Vec` or // linked list on the stack would need to be built, before any printing. match self.try_print_visible_def_path_recur(visible_parent, callers)? { - (cx, false) => return Ok((cx, false)), - (cx, true) => self = cx, + false => return Ok(false), + true => {} } callers.pop(); - - Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true)) + self.path_append(|_| Ok(()), &DisambiguatedDefPathData { data, disambiguator: 0 })?; + Ok(true) } fn pretty_path_qualified( - self, + &mut self, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { if trait_ref.is_none() { // Inherent impls. Try to print `Foo::bar` for an inherent // impl on `Foo`, but fallback to `::bar` if self-type is @@ -601,26 +604,26 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } - self.generic_delimiters(|mut cx| { + self.generic_delimiters(|cx| { define_scoped_cx!(cx); p!(print(self_ty)); if let Some(trait_ref) = trait_ref { p!(" as ", print(trait_ref.print_only_trait_path())); } - Ok(cx) + Ok(()) }) } fn pretty_path_append_impl( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; - self.generic_delimiters(|mut cx| { + self.generic_delimiters(|cx| { define_scoped_cx!(cx); p!("impl "); @@ -629,11 +632,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } p!(print(self_ty)); - Ok(cx) + Ok(()) }) } - fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result { + fn pretty_print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { define_scoped_cx!(self); match *ty.kind() { @@ -679,7 +682,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::Infer(infer_ty) => { if self.should_print_verbose() { p!(write("{:?}", ty.kind())); - return Ok(self); + return Ok(()); } if let ty::TyVar(ty_vid) = infer_ty { @@ -696,7 +699,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::Param(ref param_ty) => p!(print(param_ty)), ty::Bound(debruijn, bound_ty) => match bound_ty.kind { ty::BoundTyKind::Anon => { - rustc_type_ir::debug_bound_var(&mut self, debruijn, bound_ty.var)? + rustc_type_ir::debug_bound_var(self, debruijn, bound_ty.var)? } ty::BoundTyKind::Param(_, s) => match self.should_print_verbose() { true => p!(write("{:?}", ty.kind())), @@ -751,7 +754,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if self.should_print_verbose() { // FIXME(eddyb) print this with `print_def_path`. p!(write("Opaque({:?}, {})", def_id, args.print_as_list())); - return Ok(self); + return Ok(()); } let parent = self.tcx().parent(def_id); @@ -766,17 +769,17 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // If the type alias directly starts with the `impl` of the // opaque type we're printing, then skip the `::{opaque#1}`. p!(print_def_path(parent, args)); - return Ok(self); + return Ok(()); } } // Complex opaque type, e.g. `type Foo = (i32, impl Debug);` p!(print_def_path(def_id, args)); - return Ok(self); + return Ok(()); } _ => { if with_no_queries() { p!(print_def_path(def_id, &[])); - return Ok(self); + return Ok(()); } else { return self.pretty_print_opaque_impl_type(def_id, args); } @@ -817,7 +820,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if !args.as_coroutine().is_valid() { p!("unavailable"); } else { - self = self.comma_sep(args.as_coroutine().upvar_tys().iter())?; + self.comma_sep(args.as_coroutine().upvar_tys().iter())?; } p!(")"); @@ -887,7 +890,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { print(args.as_closure().sig_as_fn_ptr_ty()) ); p!(" upvar_tys=("); - self = self.comma_sep(args.as_closure().upvar_tys().iter())?; + self.comma_sep(args.as_closure().upvar_tys().iter())?; p!(")"); } } @@ -897,14 +900,14 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::Slice(ty) => p!("[", print(ty), "]"), } - Ok(self) + Ok(()) } fn pretty_print_opaque_impl_type( - mut self, + &mut self, def_id: DefId, args: &'tcx ty::List>, - ) -> Result { + ) -> Result<(), PrintError> { let tcx = self.tcx(); // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`, @@ -962,7 +965,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, "{}", if first { "" } else { " + " })?; write!(self, "{}", if paren_needed { "(" } else { "" })?; - self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| { + self.wrap_binder(&fn_once_trait_ref, |trait_ref, cx| { define_scoped_cx!(cx); // Get the (single) generic ty (the args) of this FnOnce trait ref. let generics = tcx.generics_of(trait_ref.def_id); @@ -1019,7 +1022,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } - Ok(cx) + Ok(()) })?; } @@ -1027,7 +1030,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { for (trait_ref, assoc_items) in traits { write!(self, "{}", if first { "" } else { " + " })?; - self = self.wrap_binder(&trait_ref, |trait_ref, mut cx| { + self.wrap_binder(&trait_ref, |trait_ref, cx| { define_scoped_cx!(cx); p!(print(trait_ref.print_only_trait_name())); @@ -1091,7 +1094,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } first = false; - Ok(cx) + Ok(()) })?; } @@ -1104,7 +1107,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if !FORCE_TRIMMED_PATH.with(|flag| flag.get()) { for re in lifetimes { write!(self, " + ")?; - self = self.print_region(re)?; + self.print_region(re)?; } } @@ -1117,11 +1120,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { { let num_args = self.tcx().generics_of(fn_def_id).count(); write!(self, " {{ ")?; - self = self.print_def_path(fn_def_id, &args[..num_args])?; + self.print_def_path(fn_def_id, &args[..num_args])?; write!(self, "() }}")?; } - Ok(self) + Ok(()) } /// Insert the trait ref and optionally a projection type associated with it into either the @@ -1172,9 +1175,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } fn pretty_print_inherent_projection( - self, + &mut self, alias_ty: &ty::AliasTy<'tcx>, - ) -> Result { + ) -> Result<(), PrintError> { let def_key = self.tcx().def_key(alias_ty.def_id); self.path_generic_args( |cx| { @@ -1196,14 +1199,14 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } fn pretty_print_dyn_existential( - mut self, + &mut self, predicates: &'tcx ty::List>, - ) -> Result { + ) -> Result<(), PrintError> { // Generate the main trait ref, including associated types. let mut first = true; if let Some(principal) = predicates.principal() { - self = self.wrap_binder(&principal, |principal, mut cx| { + self.wrap_binder(&principal, |principal, cx| { define_scoped_cx!(cx); p!(print_def_path(principal.def_id, &[])); @@ -1243,8 +1246,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { }); if !args.is_empty() || !projections.is_empty() { - p!(generic_delimiters(|mut cx| { - cx = cx.comma_sep(args.iter().copied())?; + p!(generic_delimiters(|cx| { + cx.comma_sep(args.iter().copied())?; if !args.is_empty() && !projections.is_empty() { write!(cx, ", ")?; } @@ -1252,7 +1255,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { })); } } - Ok(cx) + Ok(()) })?; first = false; @@ -1283,15 +1286,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { p!(print_def_path(def_id, &[])); } - Ok(self) + Ok(()) } fn pretty_fn_sig( - mut self, + &mut self, inputs: &[Ty<'tcx>], c_variadic: bool, output: Ty<'tcx>, - ) -> Result { + ) -> Result<(), PrintError> { define_scoped_cx!(self); p!("(", comma_sep(inputs.iter().copied())); @@ -1306,28 +1309,28 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { p!(" -> ", print(output)); } - Ok(self) + Ok(()) } fn pretty_print_const( - mut self, + &mut self, ct: ty::Const<'tcx>, print_ty: bool, - ) -> Result { + ) -> Result<(), PrintError> { define_scoped_cx!(self); if self.should_print_verbose() { p!(write("{:?}", ct)); - return Ok(self); + return Ok(()); } macro_rules! print_underscore { () => {{ if print_ty { - self = self.typed_value( - |mut this| { + self.typed_value( + |this| { write!(this, "_")?; - Ok(this) + Ok(()) }, |this| this.print_type(ct.ty()), ": ", @@ -1378,7 +1381,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::ConstKind::Bound(debruijn, bound_var) => { - rustc_type_ir::debug_bound_var(&mut self, debruijn, bound_var)? + rustc_type_ir::debug_bound_var(self, debruijn, bound_var)? } ty::ConstKind::Placeholder(placeholder) => p!(write("{placeholder:?}")), // FIXME(generic_const_exprs): @@ -1386,10 +1389,14 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::ConstKind::Expr(_) => p!("{{const expr}}"), ty::ConstKind::Error(_) => p!("{{const error}}"), }; - Ok(self) + Ok(()) } - fn pretty_print_const_scalar(self, scalar: Scalar, ty: Ty<'tcx>) -> Result { + fn pretty_print_const_scalar( + &mut self, + scalar: Scalar, + ty: Ty<'tcx>, + ) -> Result<(), PrintError> { match scalar { Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty), Scalar::Int(int) => { @@ -1399,10 +1406,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } fn pretty_print_const_scalar_ptr( - mut self, + &mut self, ptr: Pointer, ty: Ty<'tcx>, - ) -> Result { + ) -> Result<(), PrintError> { define_scoped_cx!(self); let (alloc_id, offset) = ptr.into_parts(); @@ -1433,7 +1440,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { Some(GlobalAlloc::VTable(..)) => p!(""), None => p!(""), } - return Ok(self); + return Ok(()); } } } @@ -1444,27 +1451,27 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if let Some(GlobalAlloc::Function(instance)) = self.tcx().try_get_global_alloc(alloc_id) { - self = self.typed_value( + self.typed_value( |this| this.print_value_path(instance.def_id(), instance.args), |this| this.print_type(ty), " as ", )?; - return Ok(self); + return Ok(()); } } _ => {} } // Any pointer values not covered by a branch above - self = self.pretty_print_const_pointer(ptr, ty)?; - Ok(self) + self.pretty_print_const_pointer(ptr, ty)?; + Ok(()) } fn pretty_print_const_scalar_int( - mut self, + &mut self, int: ScalarInt, ty: Ty<'tcx>, print_ty: bool, - ) -> Result { + ) -> Result<(), PrintError> { define_scoped_cx!(self); match ty.kind() { @@ -1491,10 +1498,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // Pointer types ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => { let data = int.assert_bits(self.tcx().data_layout.pointer_size); - self = self.typed_value( - |mut this| { + self.typed_value( + |this| { write!(this, "0x{data:x}")?; - Ok(this) + Ok(()) }, |this| this.print_type(ty), " as ", @@ -1502,57 +1509,57 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } // Nontrivial types with scalar bit representation _ => { - let print = |mut this: Self| { + let print = |this: &mut Self| { if int.size() == Size::ZERO { write!(this, "transmute(())")?; } else { write!(this, "transmute(0x{int:x})")?; } - Ok(this) + Ok(()) }; - self = if print_ty { + if print_ty { self.typed_value(print, |this| this.print_type(ty), ": ")? } else { print(self)? }; } } - Ok(self) + Ok(()) } /// This is overridden for MIR printing because we only want to hide alloc ids from users, not /// from MIR where it is actually useful. fn pretty_print_const_pointer( - self, + &mut self, _: Pointer, ty: Ty<'tcx>, - ) -> Result { + ) -> Result<(), PrintError> { self.typed_value( - |mut this| { + |this| { this.write_str("&_")?; - Ok(this) + Ok(()) }, |this| this.print_type(ty), ": ", ) } - fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result { + fn pretty_print_byte_str(&mut self, byte_str: &'tcx [u8]) -> Result<(), PrintError> { write!(self, "b\"{}\"", byte_str.escape_ascii())?; - Ok(self) + Ok(()) } fn pretty_print_const_valtree( - mut self, + &mut self, valtree: ty::ValTree<'tcx>, ty: Ty<'tcx>, print_ty: bool, - ) -> Result { + ) -> Result<(), PrintError> { define_scoped_cx!(self); if self.should_print_verbose() { p!(write("ValTree({:?}: ", valtree), print(ty), ")"); - return Ok(self); + return Ok(()); } let u8_type = self.tcx().types.u8; @@ -1573,12 +1580,12 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { bug!("expected to convert valtree to raw bytes for type {:?}", ty) }); p!(write("{:?}", String::from_utf8_lossy(bytes))); - return Ok(self); + return Ok(()); } _ => { p!("&"); p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty)); - return Ok(self); + return Ok(()); } }, (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => { @@ -1587,7 +1594,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { }); p!("*"); p!(pretty_print_byte_str(bytes)); - return Ok(self); + return Ok(()); } // Aggregates, printed as array/tuple/struct/variant construction syntax. (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => { @@ -1606,10 +1613,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { p!(")"); } ty::Adt(def, _) if def.variants().is_empty() => { - self = self.typed_value( - |mut this| { + self.typed_value( + |this| { write!(this, "unreachable()")?; - Ok(this) + Ok(()) }, |this| this.print_type(ty), ": ", @@ -1641,7 +1648,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } _ => unreachable!(), } - return Ok(self); + return Ok(()); } (ty::ValTree::Leaf(leaf), ty::Ref(_, inner_ty, _)) => { p!(write("&")); @@ -1664,18 +1671,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if print_ty { p!(": ", print(ty)); } - Ok(self) + Ok(()) } - fn pretty_closure_as_impl( - mut self, - closure: ty::ClosureArgs<'tcx>, - ) -> Result { + fn pretty_closure_as_impl(&mut self, closure: ty::ClosureArgs<'tcx>) -> Result<(), PrintError> { let sig = closure.sig(); let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn); write!(self, "impl ")?; - self.wrap_binder(&sig, |sig, mut cx| { + self.wrap_binder(&sig, |sig, cx| { define_scoped_cx!(cx); p!(print(kind), "("); @@ -1691,7 +1695,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { p!(" -> ", print(sig.output())); } - Ok(cx) + Ok(()) }) } @@ -1709,7 +1713,7 @@ pub(crate) fn pretty_print_const<'tcx>( let literal = tcx.lift(c).unwrap(); let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); cx.print_alloc_ids = true; - let cx = cx.pretty_print_const(literal, print_types)?; + cx.pretty_print_const(literal, print_types)?; fmt.write_str(&cx.into_buffer())?; Ok(()) }) @@ -1760,6 +1764,16 @@ impl<'a, 'tcx> FmtPrinter<'a, 'tcx> { Self::new_with_limit(tcx, ns, limit) } + pub fn print_string( + tcx: TyCtxt<'tcx>, + ns: Namespace, + f: impl FnOnce(&mut Self) -> Result<(), PrintError>, + ) -> Result { + let mut c = FmtPrinter::new(tcx, ns); + f(&mut c)?; + Ok(c.into_buffer()) + } + pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self { FmtPrinter(Box::new(FmtPrinterData { tcx, @@ -1820,7 +1834,8 @@ impl<'t> TyCtxt<'t> { let def_id = def_id.into_query_param(); let ns = guess_def_namespace(self, def_id); debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::new(self, ns).print_def_path(def_id, args).unwrap().into_buffer() + + FmtPrinter::print_string(self, ns, |cx| cx.print_def_path(def_id, args)).unwrap() } pub fn value_path_str_with_args( @@ -1831,7 +1846,8 @@ impl<'t> TyCtxt<'t> { let def_id = def_id.into_query_param(); let ns = guess_def_namespace(self, def_id); debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::new(self, ns).print_value_path(def_id, args).unwrap().into_buffer() + + FmtPrinter::print_string(self, ns, |cx| cx.print_value_path(def_id, args)).unwrap() } } @@ -1848,21 +1864,21 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { } fn print_def_path( - mut self, + &mut self, def_id: DefId, args: &'tcx [GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { define_scoped_cx!(self); if args.is_empty() { match self.try_print_trimmed_def_path(def_id)? { - (cx, true) => return Ok(cx), - (cx, false) => self = cx, + true => return Ok(()), + false => {} } match self.try_print_visible_def_path(def_id)? { - (cx, true) => return Ok(cx), - (cx, false) => self = cx, + true => return Ok(()), + false => {} } } @@ -1883,7 +1899,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id }; let span = self.tcx.def_span(def_id); - self = self.print_def_path(parent_def_id, &[])?; + self.print_def_path(parent_def_id, &[])?; // HACK(eddyb) copy of `path_append` to avoid // constructing a `DisambiguatedDefPathData`. @@ -1899,40 +1915,40 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { )?; self.empty_path = false; - return Ok(self); + return Ok(()); } } self.default_print_def_path(def_id, args) } - fn print_region(self, region: ty::Region<'tcx>) -> Result { + fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError> { self.pretty_print_region(region) } - fn print_type(mut self, ty: Ty<'tcx>) -> Result { + fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { if self.type_length_limit.value_within_limit(self.printed_type_count) { self.printed_type_count += 1; self.pretty_print_type(ty) } else { self.truncated = true; write!(self, "...")?; - Ok(self) + Ok(()) } } fn print_dyn_existential( - self, + &mut self, predicates: &'tcx ty::List>, - ) -> Result { + ) -> Result<(), PrintError> { self.pretty_print_dyn_existential(predicates) } - fn print_const(self, ct: ty::Const<'tcx>) -> Result { + fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> { self.pretty_print_const(ct, false) } - fn path_crate(mut self, cnum: CrateNum) -> Result { + fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.empty_path = true; if cnum == LOCAL_CRATE { if self.tcx.sess.at_least_rust_2018() { @@ -1946,52 +1962,52 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { write!(self, "{}", self.tcx.crate_name(cnum))?; self.empty_path = false; } - Ok(self) + Ok(()) } fn path_qualified( - mut self, + &mut self, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { - self = self.pretty_path_qualified(self_ty, trait_ref)?; + ) -> Result<(), PrintError> { + self.pretty_path_qualified(self_ty, trait_ref)?; self.empty_path = false; - Ok(self) + Ok(()) } fn path_append_impl( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { - self = self.pretty_path_append_impl( - |mut cx| { - cx = print_prefix(cx)?; + ) -> Result<(), PrintError> { + self.pretty_path_append_impl( + |cx| { + print_prefix(cx)?; if !cx.empty_path { write!(cx, "::")?; } - Ok(cx) + Ok(()) }, self_ty, trait_ref, )?; self.empty_path = false; - Ok(self) + Ok(()) } fn path_append( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs. if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data { - return Ok(self); + return Ok(()); } let name = disambiguated_data.data.name(); @@ -2006,19 +2022,19 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { } let verbose = self.should_print_verbose(); - disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?; + disambiguated_data.fmt_maybe_verbose(self, verbose)?; self.empty_path = false; - Ok(self) + Ok(()) } fn path_generic_args( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, args: &[GenericArg<'tcx>], - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; let tcx = self.tcx; @@ -2052,7 +2068,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { } self.generic_delimiters(|cx| cx.comma_sep(args.into_iter())) } else { - Ok(self) + Ok(()) } } } @@ -2071,29 +2087,29 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { } fn print_value_path( - mut self, + &mut self, def_id: DefId, args: &'tcx [GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { let was_in_value = std::mem::replace(&mut self.in_value, true); - self = self.print_def_path(def_id, args)?; + self.print_def_path(def_id, args)?; self.in_value = was_in_value; - Ok(self) + Ok(()) } - fn in_binder(self, value: &ty::Binder<'tcx, T>) -> Result + fn in_binder(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError> where T: Print<'tcx, Self> + TypeFoldable>, { self.pretty_in_binder(value) } - fn wrap_binder Result>( - self, + fn wrap_binder Result<(), PrintError>>( + &mut self, value: &ty::Binder<'tcx, T>, f: C, - ) -> Result + ) -> Result<(), PrintError> where T: Print<'tcx, Self> + TypeFoldable>, { @@ -2101,33 +2117,33 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { } fn typed_value( - mut self, - f: impl FnOnce(Self) -> Result, - t: impl FnOnce(Self) -> Result, + &mut self, + f: impl FnOnce(&mut Self) -> Result<(), PrintError>, + t: impl FnOnce(&mut Self) -> Result<(), PrintError>, conversion: &str, - ) -> Result { + ) -> Result<(), PrintError> { self.write_str("{")?; - self = f(self)?; + f(self)?; self.write_str(conversion)?; let was_in_value = std::mem::replace(&mut self.in_value, false); - self = t(self)?; + t(self)?; self.in_value = was_in_value; self.write_str("}")?; - Ok(self) + Ok(()) } fn generic_delimiters( - mut self, - f: impl FnOnce(Self) -> Result, - ) -> Result { + &mut self, + f: impl FnOnce(&mut Self) -> Result<(), PrintError>, + ) -> Result<(), PrintError> { write!(self, "<")?; let was_in_value = std::mem::replace(&mut self.in_value, false); - let mut inner = f(self)?; - inner.in_value = was_in_value; + f(self)?; + self.in_value = was_in_value; - write!(inner, ">")?; - Ok(inner) + write!(self, ">")?; + Ok(()) } fn should_print_region(&self, region: ty::Region<'tcx>) -> bool { @@ -2176,18 +2192,18 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { } fn pretty_print_const_pointer( - self, + &mut self, p: Pointer, ty: Ty<'tcx>, - ) -> Result { - let print = |mut this: Self| { + ) -> Result<(), PrintError> { + let print = |this: &mut Self| { define_scoped_cx!(this); if this.print_alloc_ids { p!(write("{:?}", p)); } else { p!("&_"); } - Ok(this) + Ok(()) }; self.typed_value(print, |this| this.print_type(ty), ": ") } @@ -2195,19 +2211,19 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`. impl<'tcx> FmtPrinter<'_, 'tcx> { - pub fn pretty_print_region(mut self, region: ty::Region<'tcx>) -> Result { + pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> { define_scoped_cx!(self); // Watch out for region highlights. let highlight = self.region_highlight_mode; if let Some(n) = highlight.region_highlighted(region) { p!(write("'{}", n)); - return Ok(self); + return Ok(()); } if self.should_print_verbose() { p!(write("{:?}", region)); - return Ok(self); + return Ok(()); } let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions; @@ -2220,7 +2236,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { ty::ReEarlyBound(ref data) => { if data.name != kw::Empty { p!(write("{}", data.name)); - return Ok(self); + return Ok(()); } } ty::ReLateBound(_, ty::BoundRegion { kind: br, .. }) @@ -2232,32 +2248,32 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { && br.is_named() { p!(write("{}", name)); - return Ok(self); + return Ok(()); } if let Some((region, counter)) = highlight.highlight_bound_region { if br == region { p!(write("'{}", counter)); - return Ok(self); + return Ok(()); } } } ty::ReVar(region_vid) if identify_regions => { p!(write("{:?}", region_vid)); - return Ok(self); + return Ok(()); } ty::ReVar(_) => {} ty::ReErased => {} ty::ReError(_) => {} ty::ReStatic => { p!("'static"); - return Ok(self); + return Ok(()); } } p!("'_"); - Ok(self) + Ok(()) } } @@ -2340,9 +2356,9 @@ impl<'a, 'tcx> ty::TypeFolder> for RegionFolder<'a, 'tcx> { // `region_index` and `used_region_names`. impl<'tcx> FmtPrinter<'_, 'tcx> { pub fn name_all_regions( - mut self, + &mut self, value: &ty::Binder<'tcx, T>, - ) -> Result<(Self, T, BTreeMap>), fmt::Error> + ) -> Result<(T, BTreeMap>), fmt::Error> where T: Print<'tcx, Self> + TypeFoldable>, { @@ -2417,10 +2433,10 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { // anyways. let (new_value, map) = if self.should_print_verbose() { for var in value.bound_vars().iter() { - start_or_continue(&mut self, "for<", ", "); + start_or_continue(self, "for<", ", "); write!(self, "{var:?}")?; } - start_or_continue(&mut self, "", "> "); + start_or_continue(self, "", "> "); (value.clone().skip_binder(), BTreeMap::default()) } else { let tcx = self.tcx; @@ -2484,8 +2500,8 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { }; if !trim_path { - start_or_continue(&mut self, "for<", ", "); - do_continue(&mut self, name); + start_or_continue(self, "for<", ", "); + do_continue(self, name); } ty::Region::new_late_bound( tcx, @@ -2502,42 +2518,42 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { let new_value = value.clone().skip_binder().fold_with(&mut folder); let region_map = folder.region_map; if !trim_path { - start_or_continue(&mut self, "", "> "); + start_or_continue(self, "", "> "); } (new_value, region_map) }; self.binder_depth += 1; self.region_index = region_index; - Ok((self, new_value, map)) + Ok((new_value, map)) } - pub fn pretty_in_binder(self, value: &ty::Binder<'tcx, T>) -> Result + pub fn pretty_in_binder(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), fmt::Error> where T: Print<'tcx, Self> + TypeFoldable>, { let old_region_index = self.region_index; - let (new, new_value, _) = self.name_all_regions(value)?; - let mut inner = new_value.print(new)?; - inner.region_index = old_region_index; - inner.binder_depth -= 1; - Ok(inner) + let (new_value, _) = self.name_all_regions(value)?; + new_value.print(self)?; + self.region_index = old_region_index; + self.binder_depth -= 1; + Ok(()) } - pub fn pretty_wrap_binder Result>( - self, + pub fn pretty_wrap_binder Result<(), fmt::Error>>( + &mut self, value: &ty::Binder<'tcx, T>, f: C, - ) -> Result + ) -> Result<(), fmt::Error> where T: Print<'tcx, Self> + TypeFoldable>, { let old_region_index = self.region_index; - let (new, new_value, _) = self.name_all_regions(value)?; - let mut inner = f(&new_value, new)?; - inner.region_index = old_region_index; - inner.binder_depth -= 1; - Ok(inner) + let (new_value, _) = self.name_all_regions(value)?; + f(&new_value, self)?; + self.region_index = old_region_index; + self.binder_depth -= 1; + Ok(()) } fn prepare_region_info(&mut self, value: &ty::Binder<'tcx, T>) @@ -2597,7 +2613,7 @@ impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T> where T: Print<'tcx, P> + TypeFoldable>, { - fn print(&self, cx: P) -> Result { + fn print(&self, cx: &mut P) -> Result<(), PrintError> { cx.in_binder(self) } } @@ -2607,10 +2623,10 @@ where T: Print<'tcx, P>, U: Print<'tcx, P>, { - fn print(&self, mut cx: P) -> Result { + fn print(&self, cx: &mut P) -> Result<(), PrintError> { define_scoped_cx!(cx); p!(print(self.0), ": ", print(self.1)); - Ok(cx) + Ok(()) } } @@ -2620,9 +2636,10 @@ macro_rules! forward_display_to_print { $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { - let cx = tcx.lift(*self) + let mut cx = FmtPrinter::new(tcx, Namespace::TypeNS); + tcx.lift(*self) .expect("could not lift for printing") - .print(FmtPrinter::new(tcx, Namespace::TypeNS))?; + .print(&mut cx)?; f.write_str(&cx.into_buffer())?; Ok(()) }) @@ -2634,13 +2651,13 @@ macro_rules! forward_display_to_print { macro_rules! define_print_and_forward_display { (($self:ident, $cx:ident): $($ty:ty $print:block)+) => { $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty { - fn print(&$self, $cx: P) -> Result { + fn print(&$self, $cx: &mut P) -> Result<(), PrintError> { #[allow(unused_mut)] let mut $cx = $cx; define_scoped_cx!($cx); let _: () = $print; #[allow(unreachable_code)] - Ok($cx) + Ok(()) } })+ diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 012bb74941286..bf2e61b23b206 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -22,11 +22,10 @@ impl fmt::Debug for ty::TraitDef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { with_no_trimmed_paths!({ - f.write_str( - &FmtPrinter::new(tcx, Namespace::TypeNS) - .print_def_path(self.def_id, &[])? - .into_buffer(), - ) + let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |cx| { + cx.print_def_path(self.def_id, &[]) + })?; + f.write_str(&s) }) }) } @@ -36,11 +35,10 @@ impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { with_no_trimmed_paths!({ - f.write_str( - &FmtPrinter::new(tcx, Namespace::TypeNS) - .print_def_path(self.did(), &[])? - .into_buffer(), - ) + let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |cx| { + cx.print_def_path(self.did(), &[]) + })?; + f.write_str(&s) }) }) } @@ -350,9 +348,8 @@ impl<'tcx> DebugWithInfcx> for ty::Const<'tcx> { let ConstKind::Value(valtree) = lifted.kind() else { bug!("we checked that this is a valtree") }; - let cx = FmtPrinter::new(tcx, Namespace::ValueNS); - let cx = - cx.pretty_print_const_valtree(valtree, lifted.ty(), /*print_ty*/ true)?; + let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); + cx.pretty_print_const_valtree(valtree, lifted.ty(), /*print_ty*/ true)?; f.write_str(&cx.into_buffer()) }); } diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 85a0be8a44c4a..2c29978173ff5 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -2,13 +2,13 @@ //! //! Currently, this pass only propagates scalar values. -use rustc_const_eval::interpret::{ImmTy, Immediate, InterpCx, OpTy, Projectable}; +use rustc_const_eval::interpret::{ImmTy, Immediate, InterpCx, OpTy, PlaceTy, Projectable}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::DefKind; use rustc_middle::mir::interpret::{AllocId, ConstAllocation, InterpResult, Scalar}; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; -use rustc_middle::ty::layout::TyAndLayout; +use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_mir_dataflow::value_analysis::{ Map, PlaceIndex, State, TrackElem, ValueAnalysis, ValueAnalysisWrapper, ValueOrPlace, @@ -16,8 +16,9 @@ use rustc_mir_dataflow::value_analysis::{ use rustc_mir_dataflow::{lattice::FlatSet, Analysis, Results, ResultsVisitor}; use rustc_span::def_id::DefId; use rustc_span::DUMMY_SP; -use rustc_target::abi::{FieldIdx, VariantIdx}; +use rustc_target::abi::{Abi, FieldIdx, Size, VariantIdx, FIRST_VARIANT}; +use crate::const_prop::throw_machine_stop_str; use crate::MirPass; // These constants are somewhat random guesses and have not been optimized. @@ -553,16 +554,151 @@ impl<'tcx, 'locals> Collector<'tcx, 'locals> { fn try_make_constant( &self, + ecx: &mut InterpCx<'tcx, 'tcx, DummyMachine>, place: Place<'tcx>, state: &State>, map: &Map, ) -> Option> { - let FlatSet::Elem(Scalar::Int(value)) = state.get(place.as_ref(), &map) else { - return None; - }; let ty = place.ty(self.local_decls, self.patch.tcx).ty; - Some(Const::Val(ConstValue::Scalar(value.into()), ty)) + let layout = ecx.layout_of(ty).ok()?; + + if layout.is_zst() { + return Some(Const::zero_sized(ty)); + } + + if layout.is_unsized() { + return None; + } + + let place = map.find(place.as_ref())?; + if layout.abi.is_scalar() + && let Some(value) = propagatable_scalar(place, state, map) + { + return Some(Const::Val(ConstValue::Scalar(value), ty)); + } + + if matches!(layout.abi, Abi::Scalar(..) | Abi::ScalarPair(..)) { + let alloc_id = ecx + .intern_with_temp_alloc(layout, |ecx, dest| { + try_write_constant(ecx, dest, place, ty, state, map) + }) + .ok()?; + return Some(Const::Val(ConstValue::Indirect { alloc_id, offset: Size::ZERO }, ty)); + } + + None + } +} + +fn propagatable_scalar( + place: PlaceIndex, + state: &State>, + map: &Map, +) -> Option { + if let FlatSet::Elem(value) = state.get_idx(place, map) && value.try_to_int().is_ok() { + // Do not attempt to propagate pointers, as we may fail to preserve their identity. + Some(value) + } else { + None + } +} + +#[instrument(level = "trace", skip(ecx, state, map))] +fn try_write_constant<'tcx>( + ecx: &mut InterpCx<'_, 'tcx, DummyMachine>, + dest: &PlaceTy<'tcx>, + place: PlaceIndex, + ty: Ty<'tcx>, + state: &State>, + map: &Map, +) -> InterpResult<'tcx> { + let layout = ecx.layout_of(ty)?; + + // Fast path for ZSTs. + if layout.is_zst() { + return Ok(()); + } + + // Fast path for scalars. + if layout.abi.is_scalar() + && let Some(value) = propagatable_scalar(place, state, map) + { + return ecx.write_immediate(Immediate::Scalar(value), dest); + } + + match ty.kind() { + // ZSTs. Nothing to do. + ty::FnDef(..) => {} + + // Those are scalars, must be handled above. + ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char => throw_machine_stop_str!("primitive type with provenance"), + + ty::Tuple(elem_tys) => { + for (i, elem) in elem_tys.iter().enumerate() { + let Some(field) = map.apply(place, TrackElem::Field(FieldIdx::from_usize(i))) else { + throw_machine_stop_str!("missing field in tuple") + }; + let field_dest = ecx.project_field(dest, i)?; + try_write_constant(ecx, &field_dest, field, elem, state, map)?; + } + } + + ty::Adt(def, args) => { + if def.is_union() { + throw_machine_stop_str!("cannot propagate unions") + } + + let (variant_idx, variant_def, variant_place, variant_dest) = if def.is_enum() { + let Some(discr) = map.apply(place, TrackElem::Discriminant) else { + throw_machine_stop_str!("missing discriminant for enum") + }; + let FlatSet::Elem(Scalar::Int(discr)) = state.get_idx(discr, map) else { + throw_machine_stop_str!("discriminant with provenance") + }; + let discr_bits = discr.assert_bits(discr.size()); + let Some((variant, _)) = def.discriminants(*ecx.tcx).find(|(_, var)| discr_bits == var.val) else { + throw_machine_stop_str!("illegal discriminant for enum") + }; + let Some(variant_place) = map.apply(place, TrackElem::Variant(variant)) else { + throw_machine_stop_str!("missing variant for enum") + }; + let variant_dest = ecx.project_downcast(dest, variant)?; + (variant, def.variant(variant), variant_place, variant_dest) + } else { + (FIRST_VARIANT, def.non_enum_variant(), place, dest.clone()) + }; + + for (i, field) in variant_def.fields.iter_enumerated() { + let ty = field.ty(*ecx.tcx, args); + let Some(field) = map.apply(variant_place, TrackElem::Field(i)) else { + throw_machine_stop_str!("missing field in ADT") + }; + let field_dest = ecx.project_field(&variant_dest, i.as_usize())?; + try_write_constant(ecx, &field_dest, field, ty, state, map)?; + } + ecx.write_discriminant(variant_idx, dest)?; + } + + // Unsupported for now. + ty::Array(_, _) + + // Do not attempt to support indirection in constants. + | ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Str | ty::Slice(_) + + | ty::Never + | ty::Foreign(..) + | ty::Alias(..) + | ty::Param(_) + | ty::Bound(..) + | ty::Placeholder(..) + | ty::Closure(..) + | ty::Coroutine(..) + | ty::Dynamic(..) => throw_machine_stop_str!("unsupported type"), + + ty::Error(_) | ty::Infer(..) | ty::CoroutineWitness(..) => bug!(), } + + Ok(()) } impl<'mir, 'tcx> @@ -580,8 +716,13 @@ impl<'mir, 'tcx> ) { match &statement.kind { StatementKind::Assign(box (_, rvalue)) => { - OperandCollector { state, visitor: self, map: &results.analysis.0.map } - .visit_rvalue(rvalue, location); + OperandCollector { + state, + visitor: self, + ecx: &mut results.analysis.0.ecx, + map: &results.analysis.0.map, + } + .visit_rvalue(rvalue, location); } _ => (), } @@ -599,7 +740,12 @@ impl<'mir, 'tcx> // Don't overwrite the assignment if it already uses a constant (to keep the span). } StatementKind::Assign(box (place, _)) => { - if let Some(value) = self.try_make_constant(place, state, &results.analysis.0.map) { + if let Some(value) = self.try_make_constant( + &mut results.analysis.0.ecx, + place, + state, + &results.analysis.0.map, + ) { self.patch.assignments.insert(location, value); } } @@ -614,8 +760,13 @@ impl<'mir, 'tcx> terminator: &'mir Terminator<'tcx>, location: Location, ) { - OperandCollector { state, visitor: self, map: &results.analysis.0.map } - .visit_terminator(terminator, location); + OperandCollector { + state, + visitor: self, + ecx: &mut results.analysis.0.ecx, + map: &results.analysis.0.map, + } + .visit_terminator(terminator, location); } } @@ -670,6 +821,7 @@ impl<'tcx> MutVisitor<'tcx> for Patch<'tcx> { struct OperandCollector<'tcx, 'map, 'locals, 'a> { state: &'a State>, visitor: &'a mut Collector<'tcx, 'locals>, + ecx: &'map mut InterpCx<'tcx, 'tcx, DummyMachine>, map: &'map Map, } @@ -682,7 +834,7 @@ impl<'tcx> Visitor<'tcx> for OperandCollector<'tcx, '_, '_, '_> { location: Location, ) { if let PlaceElem::Index(local) = elem - && let Some(value) = self.visitor.try_make_constant(local.into(), self.state, self.map) + && let Some(value) = self.visitor.try_make_constant(self.ecx, local.into(), self.state, self.map) { self.visitor.patch.before_effect.insert((location, local.into()), value); } @@ -690,7 +842,9 @@ impl<'tcx> Visitor<'tcx> for OperandCollector<'tcx, '_, '_, '_> { fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) { if let Some(place) = operand.place() { - if let Some(value) = self.visitor.try_make_constant(place, self.state, self.map) { + if let Some(value) = + self.visitor.try_make_constant(self.ecx, place, self.state, self.map) + { self.visitor.patch.before_effect.insert((location, place), value); } else if !place.projection.is_empty() { // Try to propagate into `Index` projections. @@ -713,7 +867,7 @@ impl<'mir, 'tcx: 'mir> rustc_const_eval::interpret::Machine<'mir, 'tcx> for Dumm } fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>, _layout: TyAndLayout<'tcx>) -> bool { - unimplemented!() + false } fn before_access_global( @@ -725,13 +879,13 @@ impl<'mir, 'tcx: 'mir> rustc_const_eval::interpret::Machine<'mir, 'tcx> for Dumm is_write: bool, ) -> InterpResult<'tcx> { if is_write { - crate::const_prop::throw_machine_stop_str!("can't write to global"); + throw_machine_stop_str!("can't write to global"); } // If the static allocation is mutable, then we can't const prop it as its content // might be different at runtime. if alloc.inner().mutability.is_mut() { - crate::const_prop::throw_machine_stop_str!("can't access mutable globals in ConstProp"); + throw_machine_stop_str!("can't access mutable globals in ConstProp"); } Ok(()) @@ -781,7 +935,7 @@ impl<'mir, 'tcx: 'mir> rustc_const_eval::interpret::Machine<'mir, 'tcx> for Dumm _left: &rustc_const_eval::interpret::ImmTy<'tcx, Self::Provenance>, _right: &rustc_const_eval::interpret::ImmTy<'tcx, Self::Provenance>, ) -> interpret::InterpResult<'tcx, (ImmTy<'tcx, Self::Provenance>, bool)> { - crate::const_prop::throw_machine_stop_str!("can't do pointer arithmetic"); + throw_machine_stop_str!("can't do pointer arithmetic"); } fn expose_ptr( diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 5f22b89ea492f..53925eeaaa0d0 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -199,16 +199,16 @@ struct SymbolPrinter<'tcx> { // `PrettyPrinter` aka pretty printing of e.g. types in paths, // symbol names should have their own printing machinery. -impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { +impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.tcx } - fn print_region(self, _region: ty::Region<'_>) -> Result { - Ok(self) + fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { + Ok(()) } - fn print_type(mut self, ty: Ty<'tcx>) -> Result { + fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { match *ty.kind() { // Print all nominal types as paths (unlike `pretty_print_type`). ty::FnDef(def_id, args) @@ -220,17 +220,17 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { // -Zverbose flag, so we cannot reuse it here. ty::Array(ty, size) => { self.write_str("[")?; - self = self.print_type(ty)?; + self.print_type(ty)?; self.write_str("; ")?; if let Some(size) = size.try_to_target_usize(self.tcx()) { write!(self, "{size}")? } else if let ty::ConstKind::Param(param) = size.kind() { - self = param.print(self)? + param.print(self)? } else { self.write_str("_")? } self.write_str("]")?; - Ok(self) + Ok(()) } ty::Alias(ty::Inherent, _) => panic!("unexpected inherent projection"), @@ -240,21 +240,21 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { } fn print_dyn_existential( - mut self, + &mut self, predicates: &'tcx ty::List>, - ) -> Result { + ) -> Result<(), PrintError> { let mut first = true; for p in predicates { if !first { write!(self, "+")?; } first = false; - self = p.print(self)?; + p.print(self)?; } - Ok(self) + Ok(()) } - fn print_const(self, ct: ty::Const<'tcx>) -> Result { + fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> { // only print integers match (ct.kind(), ct.ty().kind()) { (ty::ConstKind::Value(ty::ValTree::Leaf(scalar)), ty::Int(_) | ty::Uint(_)) => { @@ -269,18 +269,18 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { } _ => self.write_str("_")?, } - Ok(self) + Ok(()) } - fn path_crate(self, cnum: CrateNum) -> Result { + fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.write_str(self.tcx.crate_name(cnum).as_str())?; - Ok(self) + Ok(()) } fn path_qualified( - self, + &mut self, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { // Similar to `pretty_path_qualified`, but for the other // types that are printed as paths (see `print_type` above). match self_ty.kind() { @@ -295,15 +295,15 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { } fn path_append_impl( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { self.pretty_path_append_impl( - |mut cx| { - cx = print_prefix(cx)?; + |cx| { + print_prefix(cx)?; if cx.keep_within_component { // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it. @@ -312,22 +312,22 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { cx.path.finalize_pending_component(); } - Ok(cx) + Ok(()) }, self_ty, trait_ref, ) } fn path_append( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs. if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data { - return Ok(self); + return Ok(()); } if self.keep_within_component { @@ -339,14 +339,14 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { write!(self, "{}", disambiguated_data.data)?; - Ok(self) + Ok(()) } fn path_generic_args( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, args: &[GenericArg<'tcx>], - ) -> Result { - self = print_prefix(self)?; + ) -> Result<(), PrintError> { + print_prefix(self)?; let args = args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_))); @@ -354,42 +354,42 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { if args.clone().next().is_some() { self.generic_delimiters(|cx| cx.comma_sep(args)) } else { - Ok(self) + Ok(()) } } } -impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> { +impl<'tcx> PrettyPrinter<'tcx> for SymbolPrinter<'tcx> { fn should_print_region(&self, _region: ty::Region<'_>) -> bool { false } - fn comma_sep(mut self, mut elems: impl Iterator) -> Result + fn comma_sep(&mut self, mut elems: impl Iterator) -> Result<(), PrintError> where T: Print<'tcx, Self>, { if let Some(first) = elems.next() { - self = first.print(self)?; + first.print(self)?; for elem in elems { self.write_str(",")?; - self = elem.print(self)?; + elem.print(self)?; } } - Ok(self) + Ok(()) } fn generic_delimiters( - mut self, - f: impl FnOnce(Self) -> Result, - ) -> Result { + &mut self, + f: impl FnOnce(&mut Self) -> Result<(), PrintError>, + ) -> Result<(), PrintError> { write!(self, "<")?; let kept_within_component = mem::replace(&mut self.keep_within_component, true); - self = f(self)?; + f(self)?; self.keep_within_component = kept_within_component; write!(self, ">")?; - Ok(self) + Ok(()) } } diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 89b8b1518b077..ad3d291dfa088 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -30,7 +30,7 @@ pub(super) fn mangle<'tcx>( let args = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.args); let prefix = "_R"; - let mut cx = &mut SymbolMangler { + let mut cx: SymbolMangler<'_> = SymbolMangler { tcx, start_offset: prefix.len(), paths: FxHashMap::default(), @@ -49,13 +49,13 @@ pub(super) fn mangle<'tcx>( _ => None, }; - cx = if let Some(shim_kind) = shim_kind { + if let Some(shim_kind) = shim_kind { cx.path_append_ns(|cx| cx.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap() } else { cx.print_def_path(def_id, args).unwrap() }; if let Some(instantiating_crate) = instantiating_crate { - cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); + cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); } std::mem::take(&mut cx.out) } @@ -65,7 +65,7 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>( trait_ref: ty::PolyExistentialTraitRef<'tcx>, ) -> String { // FIXME(flip1995): See comment in `mangle_typeid_for_fnabi`. - let mut cx = &mut SymbolMangler { + let mut cx = SymbolMangler { tcx, start_offset: 0, paths: FxHashMap::default(), @@ -74,7 +74,7 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>( binders: vec![], out: String::new(), }; - cx = cx.print_def_path(trait_ref.def_id(), &[]).unwrap(); + cx.print_def_path(trait_ref.def_id(), &[]).unwrap(); std::mem::take(&mut cx.out) } @@ -179,32 +179,32 @@ impl<'tcx> SymbolMangler<'tcx> { self.push(ident); } - fn path_append_ns<'a>( - mut self: &'a mut Self, - print_prefix: impl FnOnce(&'a mut Self) -> Result<&'a mut Self, PrintError>, + fn path_append_ns( + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, ns: char, disambiguator: u64, name: &str, - ) -> Result<&'a mut Self, PrintError> { + ) -> Result<(), PrintError> { self.push("N"); self.out.push(ns); - self = print_prefix(self)?; + print_prefix(self)?; self.push_disambiguator(disambiguator as u64); self.push_ident(name); - Ok(self) + Ok(()) } - fn print_backref(&mut self, i: usize) -> Result<&mut Self, PrintError> { + fn print_backref(&mut self, i: usize) -> Result<(), PrintError> { self.push("B"); self.push_integer_62((i - self.start_offset) as u64); - Ok(self) + Ok(()) } - fn in_binder<'a, T>( - mut self: &'a mut Self, + fn in_binder( + &mut self, value: &ty::Binder<'tcx, T>, - print_value: impl FnOnce(&'a mut Self, &T) -> Result<&'a mut Self, PrintError>, - ) -> Result<&'a mut Self, PrintError> + print_value: impl FnOnce(&mut Self, &T) -> Result<(), PrintError>, + ) -> Result<(), PrintError> where T: TypeVisitable>, { @@ -222,45 +222,45 @@ impl<'tcx> SymbolMangler<'tcx> { lifetime_depths.end += lifetimes; self.binders.push(BinderLevel { lifetime_depths }); - self = print_value(self, value.as_ref().skip_binder())?; + print_value(self, value.as_ref().skip_binder())?; self.binders.pop(); - Ok(self) + Ok(()) } } -impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { +impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.tcx } fn print_def_path( - mut self, + &mut self, def_id: DefId, args: &'tcx [GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { if let Some(&i) = self.paths.get(&(def_id, args)) { return self.print_backref(i); } let start = self.out.len(); - self = self.default_print_def_path(def_id, args)?; + self.default_print_def_path(def_id, args)?; // Only cache paths that do not refer to an enclosing // binder (which would change depending on context). if !args.iter().any(|k| k.has_escaping_bound_vars()) { self.paths.insert((def_id, args), start); } - Ok(self) + Ok(()) } fn print_impl_path( - mut self, + &mut self, impl_def_id: DefId, args: &'tcx [GenericArg<'tcx>], mut self_ty: Ty<'tcx>, mut impl_trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { let key = self.tcx.def_key(impl_def_id); let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id }; @@ -288,7 +288,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { // Encode impl generic params if the substitutions contain parameters (implying // polymorphization is enabled) and this isn't an inherent impl. if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) { - self = self.path_generic_args( + self.path_generic_args( |this| { this.path_append_ns( |cx| cx.print_def_path(parent_def_id, &[]), @@ -301,19 +301,19 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { )?; } else { self.push_disambiguator(key.disambiguated_data.disambiguator as u64); - self = self.print_def_path(parent_def_id, &[])?; + self.print_def_path(parent_def_id, &[])?; } - self = self_ty.print(self)?; + self_ty.print(self)?; if let Some(trait_ref) = impl_trait_ref { - self = self.print_def_path(trait_ref.def_id, trait_ref.args)?; + self.print_def_path(trait_ref.def_id, trait_ref.args)?; } - Ok(self) + Ok(()) } - fn print_region(self, region: ty::Region<'_>) -> Result { + fn print_region(&mut self, region: ty::Region<'_>) -> Result<(), PrintError> { let i = match *region { // Erased lifetimes use the index 0, for a // shorter mangling of `L_`. @@ -332,10 +332,10 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { }; self.push("L"); self.push_integer_62(i as u64); - Ok(self) + Ok(()) } - fn print_type(mut self, ty: Ty<'tcx>) -> Result { + fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { // Basic types, never cached (single-character). let basic_type = match ty.kind() { ty::Bool => "b", @@ -365,7 +365,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { }; if !basic_type.is_empty() { self.push(basic_type); - return Ok(self); + return Ok(()); } if let Some(&i) = self.types.get(&ty) { @@ -391,9 +391,9 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { hir::Mutability::Mut => "Q", }); if !r.is_erased() { - self = r.print(self)?; + r.print(self)?; } - self = ty.print(self)?; + ty.print(self)?; } ty::RawPtr(mt) => { @@ -401,23 +401,23 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { hir::Mutability::Not => "P", hir::Mutability::Mut => "O", }); - self = mt.ty.print(self)?; + mt.ty.print(self)?; } ty::Array(ty, len) => { self.push("A"); - self = ty.print(self)?; - self = self.print_const(len)?; + ty.print(self)?; + self.print_const(len)?; } ty::Slice(ty) => { self.push("S"); - self = ty.print(self)?; + ty.print(self)?; } ty::Tuple(tys) => { self.push("T"); for ty in tys.iter() { - self = ty.print(self)?; + ty.print(self)?; } self.push("E"); } @@ -428,15 +428,15 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. }) | ty::Closure(def_id, args) | ty::Coroutine(def_id, args, _) => { - self = self.print_def_path(def_id, args)?; + self.print_def_path(def_id, args)?; } ty::Foreign(def_id) => { - self = self.print_def_path(def_id, &[])?; + self.print_def_path(def_id, &[])?; } ty::FnPtr(sig) => { self.push("F"); - self = self.in_binder(&sig, |mut cx, sig| { + self.in_binder(&sig, |cx, sig| { if sig.unsafety == hir::Unsafety::Unsafe { cx.push("U"); } @@ -454,7 +454,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { } } for &ty in sig.inputs() { - cx = ty.print(cx)?; + ty.print(cx)?; } if sig.c_variadic { cx.push("v"); @@ -470,8 +470,8 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { // FIXME(dyn-star): need to update v0 mangling docs ty::DynStar => "D*", }); - self = self.print_dyn_existential(predicates)?; - self = r.print(self)?; + self.print_dyn_existential(predicates)?; + r.print(self)?; } ty::Alias(ty::Inherent, _) => bug!("symbol_names: unexpected inherent projection"), @@ -484,13 +484,13 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { if !ty.has_escaping_bound_vars() { self.types.insert(ty, start); } - Ok(self) + Ok(()) } fn print_dyn_existential( - mut self, + &mut self, predicates: &'tcx ty::List>, - ) -> Result { + ) -> Result<(), PrintError> { // Okay, so this is a bit tricky. Imagine we have a trait object like // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the // output looks really close to the syntax, where the `Bar = &'a ()` bit @@ -517,7 +517,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { // [ [{}]] [{}] // Since any predicates after the first one shouldn't change the binders, // just put them all in the binders of the first. - self = self.in_binder(&predicates[0], |mut cx, _| { + self.in_binder(&predicates[0], |cx, _| { for predicate in predicates.iter() { // It would be nice to be able to validate bound vars here, but // projections can actually include bound vars from super traits @@ -528,30 +528,30 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { // Use a type that can't appear in defaults of type parameters. let dummy_self = Ty::new_fresh(cx.tcx, 0); let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self); - cx = cx.print_def_path(trait_ref.def_id, trait_ref.args)?; + cx.print_def_path(trait_ref.def_id, trait_ref.args)?; } ty::ExistentialPredicate::Projection(projection) => { let name = cx.tcx.associated_item(projection.def_id).name; cx.push("p"); cx.push_ident(name.as_str()); - cx = match projection.term.unpack() { + match projection.term.unpack() { ty::TermKind::Ty(ty) => ty.print(cx), ty::TermKind::Const(c) => c.print(cx), }?; } ty::ExistentialPredicate::AutoTrait(def_id) => { - cx = cx.print_def_path(*def_id, &[])?; + cx.print_def_path(*def_id, &[])?; } } } - Ok(cx) + Ok(()) })?; self.push("E"); - Ok(self) + Ok(()) } - fn print_const(mut self, ct: ty::Const<'tcx>) -> Result { + fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> { // We only mangle a typed value if the const can be evaluated. let ct = ct.normalize(self.tcx, ty::ParamEnv::reveal_all()); match ct.kind() { @@ -570,12 +570,13 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { | ty::ConstKind::Error(_) => { // Never cached (single-character). self.push("p"); - return Ok(self); + return Ok(()); } } if let Some(&i) = self.consts.get(&ct) { - return self.print_backref(i); + self.print_backref(i)?; + return Ok(()); } let start = self.out.len(); @@ -583,7 +584,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { match ty.kind() { ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => { - self = ty.print(self)?; + ty.print(self)?; let mut bits = ct.eval_bits(self.tcx, ty::ParamEnv::reveal_all()); @@ -645,7 +646,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { .ty; // FIXME(const_generics): add an assert that we only do this for valtrees. let dereferenced_const = self.tcx.mk_ct_from_kind(ct.kind(), pointee_ty); - self = dereferenced_const.print(self)?; + dereferenced_const.print(self)?; } } } @@ -654,22 +655,22 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { let contents = self.tcx.destructure_const(ct); let fields = contents.fields.iter().copied(); - let print_field_list = |mut this: Self| { + let print_field_list = |this: &mut Self| { for field in fields.clone() { - this = field.print(this)?; + field.print(this)?; } this.push("E"); - Ok(this) + Ok(()) }; match *ct.ty().kind() { ty::Array(..) | ty::Slice(_) => { self.push("A"); - self = print_field_list(self)?; + print_field_list(self)?; } ty::Tuple(..) => { self.push("T"); - self = print_field_list(self)?; + print_field_list(self)?; } ty::Adt(def, args) => { let variant_idx = @@ -677,7 +678,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { let variant_def = &def.variant(variant_idx); self.push("V"); - self = self.print_def_path(variant_def.def_id, args)?; + self.print_def_path(variant_def.def_id, args)?; match variant_def.ctor_kind() { Some(CtorKind::Const) => { @@ -685,7 +686,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { } Some(CtorKind::Fn) => { self.push("T"); - self = print_field_list(self)?; + print_field_list(self)?; } None => { self.push("S"); @@ -701,7 +702,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { ); self.push_ident(field_name.unwrap_or(kw::Empty).as_str()); - self = field.print(self)?; + field.print(self)?; } self.push("E"); } @@ -720,47 +721,47 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { if !ct.has_escaping_bound_vars() { self.consts.insert(ct, start); } - Ok(self) + Ok(()) } - fn path_crate(self, cnum: CrateNum) -> Result { + fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.push("C"); let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id(); self.push_disambiguator(stable_crate_id.as_u64()); let name = self.tcx.crate_name(cnum); self.push_ident(name.as_str()); - Ok(self) + Ok(()) } fn path_qualified( - mut self, + &mut self, self_ty: Ty<'tcx>, trait_ref: Option>, - ) -> Result { + ) -> Result<(), PrintError> { assert!(trait_ref.is_some()); let trait_ref = trait_ref.unwrap(); self.push("Y"); - self = self_ty.print(self)?; + self_ty.print(self)?; self.print_def_path(trait_ref.def_id, trait_ref.args) } fn path_append_impl( - self, - _: impl FnOnce(Self) -> Result, + &mut self, + _: impl FnOnce(&mut Self) -> Result<(), PrintError>, _: &DisambiguatedDefPathData, _: Ty<'tcx>, _: Option>, - ) -> Result { + ) -> Result<(), PrintError> { // Inlined into `print_impl_path` unreachable!() } fn path_append( - self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, disambiguated_data: &DisambiguatedDefPathData, - ) -> Result { + ) -> Result<(), PrintError> { let ns = match disambiguated_data.data { // Extern block segments can be skipped, names from extern blocks // are effectively living in their parent modules. @@ -797,10 +798,10 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { } fn path_generic_args( - mut self, - print_prefix: impl FnOnce(Self) -> Result, + &mut self, + print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, args: &[GenericArg<'tcx>], - ) -> Result { + ) -> Result<(), PrintError> { // Don't print any regions if they're all erased. let print_regions = args.iter().any(|arg| match arg.unpack() { GenericArgKind::Lifetime(r) => !r.is_erased(), @@ -816,23 +817,23 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { } self.push("I"); - self = print_prefix(self)?; + print_prefix(self)?; for arg in args { match arg.unpack() { GenericArgKind::Lifetime(lt) => { - self = lt.print(self)?; + lt.print(self)?; } GenericArgKind::Type(ty) => { - self = ty.print(self)?; + ty.print(self)?; } GenericArgKind::Const(c) => { self.push("K"); - self = c.print(self)?; + c.print(self)?; } } } self.push("E"); - Ok(self) + Ok(()) } } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs index b382474213ea1..1245b4a7756e1 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs @@ -246,14 +246,10 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if pred_str.len() > 50 { // We don't need to save the type to a file, we will be talking about this type already // in a separate note when we explain the obligation, so it will be available that way. - pred_str = predicate - .print(FmtPrinter::new_with_limit( - self.tcx, - Namespace::TypeNS, - rustc_session::Limit(6), - )) - .unwrap() - .into_buffer(); + let mut cx: FmtPrinter<'_, '_> = + FmtPrinter::new_with_limit(self.tcx, Namespace::TypeNS, rustc_session::Limit(6)); + predicate.print(&mut cx).unwrap(); + pred_str = cx.into_buffer(); } let mut err = struct_span_err!( self.tcx.sess, @@ -1408,17 +1404,15 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self.maybe_detailed_projection_msg(predicate, normalized_term, expected_term) }) .unwrap_or_else(|| { - with_forced_trimmed_paths!(format!( - "type mismatch resolving `{}`", - self.resolve_vars_if_possible(predicate) - .print(FmtPrinter::new_with_limit( - self.tcx, - Namespace::TypeNS, - rustc_session::Limit(10), - )) - .unwrap() - .into_buffer() - )) + let mut cx = FmtPrinter::new_with_limit( + self.tcx, + Namespace::TypeNS, + rustc_session::Limit(10), + ); + with_forced_trimmed_paths!(format!("type mismatch resolving `{}`", { + self.resolve_vars_if_possible(predicate).print(&mut cx).unwrap(); + cx.into_buffer() + })) }); let mut diag = struct_span_err!(self.tcx.sess, obligation.cause.span, E0271, "{msg}"); @@ -1463,14 +1457,15 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ty.span, with_forced_trimmed_paths!(Cow::from(format!( "type mismatch resolving `{}`", - self.resolve_vars_if_possible(predicate) - .print(FmtPrinter::new_with_limit( + { + let mut cx = FmtPrinter::new_with_limit( self.tcx, Namespace::TypeNS, rustc_session::Limit(5), - )) - .unwrap() - .into_buffer() + ); + self.resolve_vars_if_possible(predicate).print(&mut cx).unwrap(); + cx.into_buffer() + } ))), )), _ => None, diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index eb18ecf662c14..89796761126df 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -641,13 +641,13 @@ fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant { clean::simplify::move_bounds_to_generic_parameters(&mut generics); clean::Constant { - type_: clean_middle_ty( + type_: Box::new(clean_middle_ty( ty::Binder::dummy(cx.tcx.type_of(def_id).instantiate_identity()), cx, Some(def_id), None, - ), - generics: Box::new(generics), + )), + generics, kind: clean::ConstantKind::Extern { def_id }, } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7becc156142df..125b1fecf18f3 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -259,13 +259,13 @@ fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant { let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id(); Constant { - type_: clean_middle_ty( + type_: Box::new(clean_middle_ty( ty::Binder::dummy(cx.tcx.type_of(def_id).instantiate_identity()), cx, Some(def_id), None, - ), - generics: Box::new(Generics::default()), + )), + generics: Generics::default(), kind: ConstantKind::Anonymous { body: constant.value.body }, } } @@ -276,8 +276,8 @@ pub(crate) fn clean_middle_const<'tcx>( ) -> Constant { // FIXME: instead of storing the stringified expression, store `self` directly instead. Constant { - type_: clean_middle_ty(constant.map_bound(|c| c.ty()), cx, None, None), - generics: Box::new(Generics::default()), + type_: Box::new(clean_middle_ty(constant.map_bound(|c| c.ty()), cx, None, None)), + generics: Generics::default(), kind: ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() }, } } @@ -1216,14 +1216,14 @@ fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext hir::TraitItemKind::Const(ty, Some(default)) => { let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)); AssocConstItem( - Box::new(generics), - clean_ty(ty, cx), + generics, + Box::new(clean_ty(ty, cx)), ConstantKind::Local { def_id: local_did, body: default }, ) } hir::TraitItemKind::Const(ty, None) => { let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)); - TyAssocConstItem(Box::new(generics), clean_ty(ty, cx)) + TyAssocConstItem(generics, Box::new(clean_ty(ty, cx))) } hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Body(body)); @@ -1272,7 +1272,7 @@ pub(crate) fn clean_impl_item<'tcx>( hir::ImplItemKind::Const(ty, expr) => { let generics = clean_generics(impl_.generics, cx); let default = ConstantKind::Local { def_id: local_did, body: expr }; - AssocConstItem(Box::new(generics), clean_ty(ty, cx), default) + AssocConstItem(generics, Box::new(clean_ty(ty, cx)), default) } hir::ImplItemKind::Fn(ref sig, body) => { let m = clean_function(cx, sig, impl_.generics, FunctionArgs::Body(body)); @@ -1311,18 +1311,18 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( let tcx = cx.tcx; let kind = match assoc_item.kind { ty::AssocKind::Const => { - let ty = clean_middle_ty( + let ty = Box::new(clean_middle_ty( ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()), cx, Some(assoc_item.def_id), None, - ); + )); - let mut generics = Box::new(clean_ty_generics( + let mut generics = clean_ty_generics( cx, tcx.generics_of(assoc_item.def_id), tcx.explicit_predicates_of(assoc_item.def_id), - )); + ); simplify::move_bounds_to_generic_parameters(&mut generics); let provided = match assoc_item.container { @@ -2718,8 +2718,8 @@ fn clean_maybe_renamed_item<'tcx>( StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) }) } ItemKind::Const(ty, generics, body_id) => ConstantItem(Constant { - type_: clean_ty(ty, cx), - generics: Box::new(clean_generics(generics, cx)), + type_: Box::new(clean_ty(ty, cx)), + generics: clean_generics(generics, cx), kind: ConstantKind::Local { body: body_id, def_id }, }), ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy { diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 2a54266676d0c..6a7410144fd50 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -852,9 +852,9 @@ pub(crate) enum ItemKind { ProcMacroItem(ProcMacro), PrimitiveItem(PrimitiveType), /// A required associated constant in a trait declaration. - TyAssocConstItem(Box, Type), + TyAssocConstItem(Generics, Box), /// An associated constant in a trait impl or a provided one in a trait declaration. - AssocConstItem(Box, Type, ConstantKind), + AssocConstItem(Generics, Box, ConstantKind), /// A required associated type in a trait declaration. /// /// The bounds may be non-empty if there is a `where` clause. @@ -2282,8 +2282,8 @@ pub(crate) struct Static { #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub(crate) struct Constant { - pub(crate) type_: Type, - pub(crate) generics: Box, + pub(crate) type_: Box, + pub(crate) generics: Generics, pub(crate) kind: ConstantKind, } @@ -2524,8 +2524,7 @@ mod size_asserts { static_assert_size!(GenericParamDef, 56); static_assert_size!(Generics, 16); static_assert_size!(Item, 56); - // FIXME(generic_const_items): Further reduce the size. - static_assert_size!(ItemKind, 72); + static_assert_size!(ItemKind, 56); static_assert_size!(PathSegment, 40); static_assert_size!(Type, 32); // tidy-alphabetical-end diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 17e2172a27068..563e0cffdddb9 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -177,7 +177,7 @@ impl FromWithTcx for Constant { let expr = constant.expr(tcx); let value = constant.value(tcx); let is_literal = constant.is_literal(tcx); - Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal } + Constant { type_: (*constant.type_).into_tcx(tcx), expr, value, is_literal } } } @@ -325,11 +325,11 @@ fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum { } // FIXME(generic_const_items): Add support for generic associated consts. TyAssocConstItem(_generics, ty) => { - ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None } + ItemEnum::AssocConst { type_: (*ty).into_tcx(tcx), default: None } } // FIXME(generic_const_items): Add support for generic associated consts. AssocConstItem(_generics, ty, default) => { - ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) } + ItemEnum::AssocConst { type_: (*ty).into_tcx(tcx), default: Some(default.expr(tcx)) } } TyAssocTypeItem(g, b) => ItemEnum::AssocType { generics: g.into_tcx(tcx), diff --git a/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff b/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff index ed47baa67daba..313e5dddbbba4 100644 --- a/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff +++ b/tests/mir-opt/const_debuginfo.main.ConstDebugInfo.diff @@ -41,7 +41,8 @@ + debug ((f: (bool, bool, u32)).2: u32) => const 123_u32; let _10: std::option::Option; scope 7 { - debug o => _10; +- debug o => _10; ++ debug o => const Option::::Some(99_u16); let _17: u32; let _18: u32; scope 8 { @@ -81,7 +82,7 @@ _15 = const false; _16 = const 123_u32; StorageLive(_10); - _10 = Option::::Some(const 99_u16); + _10 = const Option::::Some(99_u16); _17 = const 32_u32; _18 = const 32_u32; StorageLive(_11); @@ -97,3 +98,7 @@ } } + ALLOC0 (size: 4, align: 2) { + 01 00 63 00 │ ..c. + } + diff --git a/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-abort.diff index 2f1a70f32d03a..4569ffe483b38 100644 --- a/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-abort.diff +++ b/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-abort.diff @@ -43,7 +43,7 @@ - _6 = CheckedAdd(_4, _5); - assert(!move (_6.1: bool), "attempt to compute `{} + {}`, which would overflow", move _4, move _5) -> [success: bb1, unwind unreachable]; + _5 = const 2_i32; -+ _6 = CheckedAdd(const 1_i32, const 2_i32); ++ _6 = const (3_i32, false); + assert(!const false, "attempt to compute `{} + {}`, which would overflow", const 1_i32, const 2_i32) -> [success: bb1, unwind unreachable]; } @@ -60,7 +60,7 @@ - _10 = CheckedAdd(_9, const 1_i32); - assert(!move (_10.1: bool), "attempt to compute `{} + {}`, which would overflow", move _9, const 1_i32) -> [success: bb2, unwind unreachable]; + _9 = const i32::MAX; -+ _10 = CheckedAdd(const i32::MAX, const 1_i32); ++ _10 = const (i32::MIN, true); + assert(!const true, "attempt to compute `{} + {}`, which would overflow", const i32::MAX, const 1_i32) -> [success: bb2, unwind unreachable]; } @@ -76,5 +76,13 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC0 (size: 8, align: 4) { ++ 00 00 00 80 01 __ __ __ │ .....░░░ ++ } ++ ++ ALLOC1 (size: 8, align: 4) { ++ 03 00 00 00 00 __ __ __ │ .....░░░ } diff --git a/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-unwind.diff index 0d8a9aca3d8c5..aa7e404eb9f50 100644 --- a/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-unwind.diff +++ b/tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.panic-unwind.diff @@ -43,7 +43,7 @@ - _6 = CheckedAdd(_4, _5); - assert(!move (_6.1: bool), "attempt to compute `{} + {}`, which would overflow", move _4, move _5) -> [success: bb1, unwind continue]; + _5 = const 2_i32; -+ _6 = CheckedAdd(const 1_i32, const 2_i32); ++ _6 = const (3_i32, false); + assert(!const false, "attempt to compute `{} + {}`, which would overflow", const 1_i32, const 2_i32) -> [success: bb1, unwind continue]; } @@ -60,7 +60,7 @@ - _10 = CheckedAdd(_9, const 1_i32); - assert(!move (_10.1: bool), "attempt to compute `{} + {}`, which would overflow", move _9, const 1_i32) -> [success: bb2, unwind continue]; + _9 = const i32::MAX; -+ _10 = CheckedAdd(const i32::MAX, const 1_i32); ++ _10 = const (i32::MIN, true); + assert(!const true, "attempt to compute `{} + {}`, which would overflow", const i32::MAX, const 1_i32) -> [success: bb2, unwind continue]; } @@ -76,5 +76,13 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC0 (size: 8, align: 4) { ++ 00 00 00 80 01 __ __ __ │ .....░░░ ++ } ++ ++ ALLOC1 (size: 8, align: 4) { ++ 03 00 00 00 00 __ __ __ │ .....░░░ } diff --git a/tests/mir-opt/dataflow-const-prop/checked.rs b/tests/mir-opt/dataflow-const-prop/checked.rs index b41ac0b3d2af6..f7fac8890a057 100644 --- a/tests/mir-opt/dataflow-const-prop/checked.rs +++ b/tests/mir-opt/dataflow-const-prop/checked.rs @@ -1,7 +1,7 @@ // skip-filecheck -// EMIT_MIR_FOR_EACH_PANIC_STRATEGY // unit-test: DataflowConstProp // compile-flags: -Coverflow-checks=on +// EMIT_MIR_FOR_EACH_PANIC_STRATEGY // EMIT_MIR checked.main.DataflowConstProp.diff #[allow(arithmetic_overflow)] diff --git a/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.32bit.diff b/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.32bit.diff index 3946e7c7d96c1..798b0c041b4ec 100644 --- a/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.32bit.diff +++ b/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.32bit.diff @@ -23,7 +23,8 @@ bb0: { StorageLive(_1); - _1 = E::V1(const 0_i32); +- _1 = E::V1(const 0_i32); ++ _1 = const E::V1(0_i32); StorageLive(_2); - _3 = discriminant(_1); - switchInt(move _3) -> [0: bb3, 1: bb1, otherwise: bb2]; @@ -59,5 +60,9 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC0 (size: 8, align: 4) { ++ 00 00 00 00 00 00 00 00 │ ........ } diff --git a/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.64bit.diff index 3946e7c7d96c1..798b0c041b4ec 100644 --- a/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.64bit.diff +++ b/tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.64bit.diff @@ -23,7 +23,8 @@ bb0: { StorageLive(_1); - _1 = E::V1(const 0_i32); +- _1 = E::V1(const 0_i32); ++ _1 = const E::V1(0_i32); StorageLive(_2); - _3 = discriminant(_1); - switchInt(move _3) -> [0: bb3, 1: bb1, otherwise: bb2]; @@ -59,5 +60,9 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC0 (size: 8, align: 4) { ++ 00 00 00 00 00 00 00 00 │ ........ } diff --git a/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.32bit.diff b/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.32bit.diff index 1348b27933082..d502b19823995 100644 --- a/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.32bit.diff +++ b/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.32bit.diff @@ -44,7 +44,8 @@ StorageLive(_1); StorageLive(_2); _2 = const {ALLOC1: &E}; - _1 = (*_2); +- _1 = (*_2); ++ _1 = const E::V1(0_i32); StorageDead(_2); StorageLive(_3); - _4 = discriminant(_1); @@ -110,6 +111,10 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC3 (size: 8, align: 4) { ++ 00 00 00 00 00 00 00 00 │ ........ } ALLOC2 (static: RC, size: 4, align: 4) { diff --git a/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.64bit.diff index 66929e886d3ca..5d69572b50744 100644 --- a/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.64bit.diff +++ b/tests/mir-opt/dataflow-const-prop/enum.statics.DataflowConstProp.64bit.diff @@ -44,7 +44,8 @@ StorageLive(_1); StorageLive(_2); _2 = const {ALLOC1: &E}; - _1 = (*_2); +- _1 = (*_2); ++ _1 = const E::V1(0_i32); StorageDead(_2); StorageLive(_3); - _4 = discriminant(_1); @@ -110,6 +111,10 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC3 (size: 8, align: 4) { ++ 00 00 00 00 00 00 00 00 │ ........ } ALLOC2 (static: RC, size: 8, align: 8) { diff --git a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-abort.diff index 87bb1454c9624..2d4591ea2d3d8 100644 --- a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-abort.diff +++ b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-abort.diff @@ -23,7 +23,7 @@ StorageLive(_4); - _4 = CheckedAdd(_2, _3); - assert(!move (_4.1: bool), "attempt to compute `{} + {}`, which would overflow", _2, _3) -> [success: bb1, unwind unreachable]; -+ _4 = CheckedAdd(const u8::MAX, const 1_u8); ++ _4 = const (0_u8, true); + assert(!const true, "attempt to compute `{} + {}`, which would overflow", const u8::MAX, const 1_u8) -> [success: bb1, unwind unreachable]; } @@ -37,5 +37,9 @@ _0 = const (); return; } ++ } ++ ++ ALLOC0 (size: 2, align: 1) { ++ 00 01 │ .. } diff --git a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-unwind.diff index b2f13640a4c05..e99ac782a2ff0 100644 --- a/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-unwind.diff +++ b/tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.panic-unwind.diff @@ -23,7 +23,7 @@ StorageLive(_4); - _4 = CheckedAdd(_2, _3); - assert(!move (_4.1: bool), "attempt to compute `{} + {}`, which would overflow", _2, _3) -> [success: bb1, unwind continue]; -+ _4 = CheckedAdd(const u8::MAX, const 1_u8); ++ _4 = const (0_u8, true); + assert(!const true, "attempt to compute `{} + {}`, which would overflow", const u8::MAX, const 1_u8) -> [success: bb1, unwind continue]; } @@ -37,5 +37,9 @@ _0 = const (); return; } ++ } ++ ++ ALLOC0 (size: 2, align: 1) { ++ 00 01 │ .. } diff --git a/tests/mir-opt/dataflow-const-prop/repr_transparent.main.DataflowConstProp.diff b/tests/mir-opt/dataflow-const-prop/repr_transparent.main.DataflowConstProp.diff index 4b1a8d932c651..98bd40ab2c3da 100644 --- a/tests/mir-opt/dataflow-const-prop/repr_transparent.main.DataflowConstProp.diff +++ b/tests/mir-opt/dataflow-const-prop/repr_transparent.main.DataflowConstProp.diff @@ -17,7 +17,8 @@ bb0: { StorageLive(_1); - _1 = I32(const 0_i32); +- _1 = I32(const 0_i32); ++ _1 = const I32(0_i32); StorageLive(_2); StorageLive(_3); StorageLive(_4); @@ -31,12 +32,20 @@ StorageDead(_5); StorageDead(_4); - _2 = I32(move _3); -+ _2 = I32(const 0_i32); ++ _2 = const I32(0_i32); StorageDead(_3); _0 = const (); StorageDead(_2); StorageDead(_1); return; } ++ } ++ ++ ALLOC0 (size: 4, align: 4) { ++ 00 00 00 00 │ .... ++ } ++ ++ ALLOC1 (size: 4, align: 4) { ++ 00 00 00 00 │ .... } diff --git a/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.32bit.diff b/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.32bit.diff index e80f31ca9348a..944b061f9939b 100644 --- a/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.32bit.diff +++ b/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.32bit.diff @@ -7,13 +7,24 @@ let mut _3: i32; let mut _5: i32; let mut _6: i32; - let mut _11: BigStruct; - let mut _16: &&BigStruct; - let mut _17: &BigStruct; - let mut _18: &BigStruct; - let mut _19: &BigStruct; - let mut _20: &BigStruct; - let mut _21: &BigStruct; + let mut _10: SmallStruct; + let mut _14: &&SmallStruct; + let mut _16: f32; + let mut _17: std::option::Option; + let mut _18: &[f32]; + let mut _22: BigStruct; + let mut _26: &&BigStruct; + let mut _28: f32; + let mut _29: std::option::Option; + let mut _30: &[f64]; + let mut _31: &SmallStruct; + let mut _32: &SmallStruct; + let mut _33: &SmallStruct; + let mut _34: &SmallStruct; + let mut _35: &BigStruct; + let mut _36: &BigStruct; + let mut _37: &BigStruct; + let mut _38: &BigStruct; scope 1 { debug s => _1; let _2: i32; @@ -22,24 +33,44 @@ let _4: i32; scope 3 { debug b => _4; - let _7: S; - let _8: u8; - let _9: f32; - let _10: S; + let _7: f32; + let _8: std::option::Option; + let _9: &[f32]; scope 4 { debug a => _7; debug b => _8; debug c => _9; - debug d => _10; - let _12: S; - let _13: u8; - let _14: f32; - let _15: S; + let _11: f32; + let _12: std::option::Option; + let _13: &[f32]; scope 5 { - debug a => _12; - debug b => _13; - debug c => _14; - debug d => _15; + debug a => _11; + debug b => _12; + debug c => _13; + let _15: SmallStruct; + scope 6 { + debug ss => _15; + let _19: f32; + let _20: std::option::Option; + let _21: &[f64]; + scope 7 { + debug a => _19; + debug b => _20; + debug c => _21; + let _23: f32; + let _24: std::option::Option; + let _25: &[f64]; + scope 8 { + debug a => _23; + debug b => _24; + debug c => _25; + let _27: BigStruct; + scope 9 { + debug bs => _27; + } + } + } + } } } } @@ -48,7 +79,8 @@ bb0: { StorageLive(_1); - _1 = S(const 1_i32); +- _1 = S(const 1_i32); ++ _1 = const S(1_i32); StorageLive(_2); StorageLive(_3); - _3 = (_1.0: i32); @@ -68,47 +100,95 @@ + _4 = const 6_i32; StorageDead(_6); StorageDead(_5); - StorageLive(_11); - _11 = const _; + StorageLive(_10); + _10 = const _; StorageLive(_7); -- _7 = (_11.0: S); -+ _7 = const S(1_i32); +- _7 = (_10.0: f32); ++ _7 = const 4f32; StorageLive(_8); -- _8 = (_11.1: u8); -+ _8 = const 5_u8; +- _8 = (_10.1: std::option::Option); ++ _8 = const Option::::Some(S(1_i32)); StorageLive(_9); -- _9 = (_11.2: f32); -+ _9 = const 7f32; - StorageLive(_10); -- _10 = (_11.3: S); -+ _10 = const S(13_i32); - StorageDead(_11); - StorageLive(_16); - _16 = const {ALLOC1: &&BigStruct}; - _17 = deref_copy (*_16); + _9 = (_10.2: &[f32]); + StorageDead(_10); + StorageLive(_14); + _14 = const {ALLOC4: &&SmallStruct}; + _31 = deref_copy (*_14); + StorageLive(_11); + _32 = deref_copy (*_14); +- _11 = ((*_32).0: f32); ++ _11 = const 9f32; StorageLive(_12); - _18 = deref_copy (*_16); -- _12 = ((*_18).0: S); -+ _12 = const S(1_i32); + _33 = deref_copy (*_14); + _12 = ((*_33).1: std::option::Option); StorageLive(_13); - _19 = deref_copy (*_16); -- _13 = ((*_19).1: u8); -+ _13 = const 5_u8; - StorageLive(_14); - _20 = deref_copy (*_16); -- _14 = ((*_20).2: f32); -+ _14 = const 7f32; + _34 = deref_copy (*_14); + _13 = ((*_34).2: &[f32]); + StorageDead(_14); StorageLive(_15); - _21 = deref_copy (*_16); -- _15 = ((*_21).3: S); -+ _15 = const S(13_i32); + StorageLive(_16); +- _16 = _11; ++ _16 = const 9f32; + StorageLive(_17); + _17 = _12; + StorageLive(_18); + _18 = _13; +- _15 = SmallStruct(move _16, move _17, move _18); ++ _15 = SmallStruct(const 9f32, move _17, move _18); + StorageDead(_18); + StorageDead(_17); StorageDead(_16); + StorageLive(_22); + _22 = const _; + StorageLive(_19); +- _19 = (_22.0: f32); ++ _19 = const 25f32; + StorageLive(_20); + _20 = (_22.1: std::option::Option); + StorageLive(_21); + _21 = (_22.2: &[f64]); + StorageDead(_22); + StorageLive(_26); + _26 = const {ALLOC5: &&BigStruct}; + _35 = deref_copy (*_26); + StorageLive(_23); + _36 = deref_copy (*_26); +- _23 = ((*_36).0: f32); ++ _23 = const 82f32; + StorageLive(_24); + _37 = deref_copy (*_26); +- _24 = ((*_37).1: std::option::Option); ++ _24 = const Option::::Some(S(35_i32)); + StorageLive(_25); + _38 = deref_copy (*_26); + _25 = ((*_38).2: &[f64]); + StorageDead(_26); + StorageLive(_27); + StorageLive(_28); +- _28 = _23; ++ _28 = const 82f32; + StorageLive(_29); +- _29 = _24; ++ _29 = const Option::::Some(S(35_i32)); + StorageLive(_30); + _30 = _25; +- _27 = BigStruct(move _28, move _29, move _30); ++ _27 = BigStruct(const 82f32, const Option::::Some(S(35_i32)), move _30); + StorageDead(_30); + StorageDead(_29); + StorageDead(_28); _0 = const (); + StorageDead(_27); + StorageDead(_25); + StorageDead(_24); + StorageDead(_23); + StorageDead(_21); + StorageDead(_20); + StorageDead(_19); StorageDead(_15); - StorageDead(_14); StorageDead(_13); StorageDead(_12); - StorageDead(_10); + StorageDead(_11); StorageDead(_9); StorageDead(_8); StorageDead(_7); @@ -117,13 +197,51 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC6 (size: 8, align: 4) { ++ 01 00 00 00 23 00 00 00 │ ....#... ++ } ++ ++ ALLOC7 (size: 8, align: 4) { ++ 01 00 00 00 23 00 00 00 │ ....#... ++ } ++ ++ ALLOC8 (size: 8, align: 4) { ++ 01 00 00 00 23 00 00 00 │ ....#... ++ } ++ ++ ALLOC9 (size: 8, align: 4) { ++ 01 00 00 00 01 00 00 00 │ ........ ++ } ++ ++ ALLOC10 (size: 4, align: 4) { ++ 01 00 00 00 │ .... } - ALLOC1 (static: STAT, size: 4, align: 4) { + ALLOC5 (static: BIG_STAT, size: 4, align: 4) { ╾ALLOC0╼ │ ╾──╼ } - ALLOC0 (size: 16, align: 4) { - 01 00 00 00 00 00 e0 40 0d 00 00 00 05 __ __ __ │ .......@.....░░░ + ALLOC0 (size: 20, align: 4) { + 0x00 │ 01 00 00 00 23 00 00 00 ╾ALLOC1╼ 02 00 00 00 │ ....#...╾──╼.... + 0x10 │ 00 00 a4 42 │ ...B + } + + ALLOC1 (size: 16, align: 4) { + 00 00 00 00 00 80 46 40 00 00 00 00 00 00 52 40 │ ......F@......R@ + } + + ALLOC4 (static: SMALL_STAT, size: 4, align: 4) { + ╾ALLOC2╼ │ ╾──╼ + } + + ALLOC2 (size: 20, align: 4) { + 0x00 │ 00 00 00 00 __ __ __ __ ╾ALLOC3╼ 01 00 00 00 │ ....░░░░╾──╼.... + 0x10 │ 00 00 10 41 │ ...A + } + + ALLOC3 (size: 4, align: 4) { + 00 00 50 41 │ ..PA } diff --git a/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.64bit.diff index de9cf19719978..c2c95657a2a3d 100644 --- a/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.64bit.diff +++ b/tests/mir-opt/dataflow-const-prop/struct.main.DataflowConstProp.64bit.diff @@ -7,13 +7,24 @@ let mut _3: i32; let mut _5: i32; let mut _6: i32; - let mut _11: BigStruct; - let mut _16: &&BigStruct; - let mut _17: &BigStruct; - let mut _18: &BigStruct; - let mut _19: &BigStruct; - let mut _20: &BigStruct; - let mut _21: &BigStruct; + let mut _10: SmallStruct; + let mut _14: &&SmallStruct; + let mut _16: f32; + let mut _17: std::option::Option; + let mut _18: &[f32]; + let mut _22: BigStruct; + let mut _26: &&BigStruct; + let mut _28: f32; + let mut _29: std::option::Option; + let mut _30: &[f64]; + let mut _31: &SmallStruct; + let mut _32: &SmallStruct; + let mut _33: &SmallStruct; + let mut _34: &SmallStruct; + let mut _35: &BigStruct; + let mut _36: &BigStruct; + let mut _37: &BigStruct; + let mut _38: &BigStruct; scope 1 { debug s => _1; let _2: i32; @@ -22,24 +33,44 @@ let _4: i32; scope 3 { debug b => _4; - let _7: S; - let _8: u8; - let _9: f32; - let _10: S; + let _7: f32; + let _8: std::option::Option; + let _9: &[f32]; scope 4 { debug a => _7; debug b => _8; debug c => _9; - debug d => _10; - let _12: S; - let _13: u8; - let _14: f32; - let _15: S; + let _11: f32; + let _12: std::option::Option; + let _13: &[f32]; scope 5 { - debug a => _12; - debug b => _13; - debug c => _14; - debug d => _15; + debug a => _11; + debug b => _12; + debug c => _13; + let _15: SmallStruct; + scope 6 { + debug ss => _15; + let _19: f32; + let _20: std::option::Option; + let _21: &[f64]; + scope 7 { + debug a => _19; + debug b => _20; + debug c => _21; + let _23: f32; + let _24: std::option::Option; + let _25: &[f64]; + scope 8 { + debug a => _23; + debug b => _24; + debug c => _25; + let _27: BigStruct; + scope 9 { + debug bs => _27; + } + } + } + } } } } @@ -48,7 +79,8 @@ bb0: { StorageLive(_1); - _1 = S(const 1_i32); +- _1 = S(const 1_i32); ++ _1 = const S(1_i32); StorageLive(_2); StorageLive(_3); - _3 = (_1.0: i32); @@ -68,47 +100,95 @@ + _4 = const 6_i32; StorageDead(_6); StorageDead(_5); - StorageLive(_11); - _11 = const _; + StorageLive(_10); + _10 = const _; StorageLive(_7); -- _7 = (_11.0: S); -+ _7 = const S(1_i32); +- _7 = (_10.0: f32); ++ _7 = const 4f32; StorageLive(_8); -- _8 = (_11.1: u8); -+ _8 = const 5_u8; +- _8 = (_10.1: std::option::Option); ++ _8 = const Option::::Some(S(1_i32)); StorageLive(_9); -- _9 = (_11.2: f32); -+ _9 = const 7f32; - StorageLive(_10); -- _10 = (_11.3: S); -+ _10 = const S(13_i32); - StorageDead(_11); - StorageLive(_16); - _16 = const {ALLOC1: &&BigStruct}; - _17 = deref_copy (*_16); + _9 = (_10.2: &[f32]); + StorageDead(_10); + StorageLive(_14); + _14 = const {ALLOC4: &&SmallStruct}; + _31 = deref_copy (*_14); + StorageLive(_11); + _32 = deref_copy (*_14); +- _11 = ((*_32).0: f32); ++ _11 = const 9f32; StorageLive(_12); - _18 = deref_copy (*_16); -- _12 = ((*_18).0: S); -+ _12 = const S(1_i32); + _33 = deref_copy (*_14); + _12 = ((*_33).1: std::option::Option); StorageLive(_13); - _19 = deref_copy (*_16); -- _13 = ((*_19).1: u8); -+ _13 = const 5_u8; - StorageLive(_14); - _20 = deref_copy (*_16); -- _14 = ((*_20).2: f32); -+ _14 = const 7f32; + _34 = deref_copy (*_14); + _13 = ((*_34).2: &[f32]); + StorageDead(_14); StorageLive(_15); - _21 = deref_copy (*_16); -- _15 = ((*_21).3: S); -+ _15 = const S(13_i32); + StorageLive(_16); +- _16 = _11; ++ _16 = const 9f32; + StorageLive(_17); + _17 = _12; + StorageLive(_18); + _18 = _13; +- _15 = SmallStruct(move _16, move _17, move _18); ++ _15 = SmallStruct(const 9f32, move _17, move _18); + StorageDead(_18); + StorageDead(_17); StorageDead(_16); + StorageLive(_22); + _22 = const _; + StorageLive(_19); +- _19 = (_22.0: f32); ++ _19 = const 25f32; + StorageLive(_20); + _20 = (_22.1: std::option::Option); + StorageLive(_21); + _21 = (_22.2: &[f64]); + StorageDead(_22); + StorageLive(_26); + _26 = const {ALLOC5: &&BigStruct}; + _35 = deref_copy (*_26); + StorageLive(_23); + _36 = deref_copy (*_26); +- _23 = ((*_36).0: f32); ++ _23 = const 82f32; + StorageLive(_24); + _37 = deref_copy (*_26); +- _24 = ((*_37).1: std::option::Option); ++ _24 = const Option::::Some(S(35_i32)); + StorageLive(_25); + _38 = deref_copy (*_26); + _25 = ((*_38).2: &[f64]); + StorageDead(_26); + StorageLive(_27); + StorageLive(_28); +- _28 = _23; ++ _28 = const 82f32; + StorageLive(_29); +- _29 = _24; ++ _29 = const Option::::Some(S(35_i32)); + StorageLive(_30); + _30 = _25; +- _27 = BigStruct(move _28, move _29, move _30); ++ _27 = BigStruct(const 82f32, const Option::::Some(S(35_i32)), move _30); + StorageDead(_30); + StorageDead(_29); + StorageDead(_28); _0 = const (); + StorageDead(_27); + StorageDead(_25); + StorageDead(_24); + StorageDead(_23); + StorageDead(_21); + StorageDead(_20); + StorageDead(_19); StorageDead(_15); - StorageDead(_14); StorageDead(_13); StorageDead(_12); - StorageDead(_10); + StorageDead(_11); StorageDead(_9); StorageDead(_8); StorageDead(_7); @@ -117,13 +197,51 @@ StorageDead(_1); return; } ++ } ++ ++ ALLOC6 (size: 8, align: 4) { ++ 01 00 00 00 23 00 00 00 │ ....#... ++ } ++ ++ ALLOC7 (size: 8, align: 4) { ++ 01 00 00 00 23 00 00 00 │ ....#... ++ } ++ ++ ALLOC8 (size: 8, align: 4) { ++ 01 00 00 00 23 00 00 00 │ ....#... ++ } ++ ++ ALLOC9 (size: 8, align: 4) { ++ 01 00 00 00 01 00 00 00 │ ........ ++ } ++ ++ ALLOC10 (size: 4, align: 4) { ++ 01 00 00 00 │ .... } - ALLOC1 (static: STAT, size: 8, align: 8) { + ALLOC5 (static: BIG_STAT, size: 8, align: 8) { ╾ALLOC0╼ │ ╾──────╼ } - ALLOC0 (size: 16, align: 4) { - 01 00 00 00 00 00 e0 40 0d 00 00 00 05 __ __ __ │ .......@.....░░░ + ALLOC0 (size: 32, align: 8) { + 0x00 │ 01 00 00 00 23 00 00 00 ╾ALLOC1╼ │ ....#...╾──────╼ + 0x10 │ 02 00 00 00 00 00 00 00 00 00 a4 42 __ __ __ __ │ ...........B░░░░ + } + + ALLOC1 (size: 16, align: 8) { + 00 00 00 00 00 80 46 40 00 00 00 00 00 00 52 40 │ ......F@......R@ + } + + ALLOC4 (static: SMALL_STAT, size: 8, align: 8) { + ╾ALLOC2╼ │ ╾──────╼ + } + + ALLOC2 (size: 32, align: 8) { + 0x00 │ 00 00 00 00 __ __ __ __ ╾ALLOC3╼ │ ....░░░░╾──────╼ + 0x10 │ 01 00 00 00 00 00 00 00 00 00 10 41 __ __ __ __ │ ...........A░░░░ + } + + ALLOC3 (size: 4, align: 4) { + 00 00 50 41 │ ..PA } diff --git a/tests/mir-opt/dataflow-const-prop/struct.rs b/tests/mir-opt/dataflow-const-prop/struct.rs index 7b0646a535640..030f3c0c4dedf 100644 --- a/tests/mir-opt/dataflow-const-prop/struct.rs +++ b/tests/mir-opt/dataflow-const-prop/struct.rs @@ -6,7 +6,10 @@ struct S(i32); #[derive(Copy, Clone)] -struct BigStruct(S, u8, f32, S); +struct SmallStruct(f32, Option, &'static [f32]); + +#[derive(Copy, Clone)] +struct BigStruct(f32, Option, &'static [f64]); // EMIT_MIR struct.main.DataflowConstProp.diff fn main() { @@ -15,9 +18,21 @@ fn main() { s.0 = 3; let b = a + s.0; - const VAL: BigStruct = BigStruct(S(1), 5, 7., S(13)); - let BigStruct(a, b, c, d) = VAL; + const SMALL_VAL: SmallStruct = SmallStruct(4., Some(S(1)), &[]); + let SmallStruct(a, b, c) = SMALL_VAL; + + static SMALL_STAT: &SmallStruct = &SmallStruct(9., None, &[13.]); + let SmallStruct(a, b, c) = *SMALL_STAT; + + let ss = SmallStruct(a, b, c); + + const BIG_VAL: BigStruct = BigStruct(25., None, &[]); + let BigStruct(a, b, c) = BIG_VAL; + + static BIG_STAT: &BigStruct = &BigStruct(82., Some(S(35)), &[45., 72.]); + let BigStruct(a, b, c) = *BIG_STAT; - static STAT: &BigStruct = &BigStruct(S(1), 5, 7., S(13)); - let BigStruct(a, b, c, d) = *STAT; + // We arbitrarily limit the size of synthetized values to 4 pointers. + // `BigStruct` can be read, but we will keep a MIR aggregate for this. + let bs = BigStruct(a, b, c); } diff --git a/tests/mir-opt/dataflow-const-prop/transmute.rs b/tests/mir-opt/dataflow-const-prop/transmute.rs index 02e4f1e501346..bb85e4586787e 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.rs +++ b/tests/mir-opt/dataflow-const-prop/transmute.rs @@ -52,8 +52,8 @@ pub unsafe fn undef_union_as_integer() -> u32 { // EMIT_MIR transmute.unreachable_direct.DataflowConstProp.diff pub unsafe fn unreachable_direct() -> ! { // CHECK-LABEL: fn unreachable_direct( - // CHECK: [[unit:_.*]] = (); - // CHECK: move [[unit]] as Never (Transmute); + // CHECK: = const (); + // CHECK: = const ZeroSized: Never; let x: Never = unsafe { transmute(()) }; match x {} } diff --git a/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.32bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.32bit.diff index fc0634b1f8fc9..fb28aa8f6d9cf 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.32bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.32bit.diff @@ -11,8 +11,10 @@ bb0: { StorageLive(_1); StorageLive(_2); - _2 = (); - _1 = Union32 { value: move _2 }; +- _2 = (); +- _1 = Union32 { value: move _2 }; ++ _2 = const (); ++ _1 = Union32 { value: const () }; StorageDead(_2); _0 = move _1 as u32 (Transmute); StorageDead(_1); diff --git a/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.64bit.diff index fc0634b1f8fc9..fb28aa8f6d9cf 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.64bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.undef_union_as_integer.DataflowConstProp.64bit.diff @@ -11,8 +11,10 @@ bb0: { StorageLive(_1); StorageLive(_2); - _2 = (); - _1 = Union32 { value: move _2 }; +- _2 = (); +- _1 = Union32 { value: move _2 }; ++ _2 = const (); ++ _1 = Union32 { value: const () }; StorageDead(_2); _0 = move _1 as u32 (Transmute); StorageDead(_1); diff --git a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.32bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.32bit.diff index acbb5cd1bc733..c8d4d6edba1e8 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.32bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.32bit.diff @@ -14,8 +14,10 @@ bb0: { StorageLive(_1); StorageLive(_2); - _2 = (); - _1 = move _2 as Never (Transmute); +- _2 = (); +- _1 = move _2 as Never (Transmute); ++ _2 = const (); ++ _1 = const ZeroSized: Never; unreachable; } } diff --git a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.64bit.diff index acbb5cd1bc733..c8d4d6edba1e8 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.64bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_direct.DataflowConstProp.64bit.diff @@ -14,8 +14,10 @@ bb0: { StorageLive(_1); StorageLive(_2); - _2 = (); - _1 = move _2 as Never (Transmute); +- _2 = (); +- _1 = move _2 as Never (Transmute); ++ _2 = const (); ++ _1 = const ZeroSized: Never; unreachable; } } diff --git a/tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.diff b/tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.32bit.diff similarity index 57% rename from tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.diff rename to tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.32bit.diff index 5e385d21ec602..f5723cac7d9c8 100644 --- a/tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.diff +++ b/tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.32bit.diff @@ -11,6 +11,9 @@ let mut _8: i32; let mut _9: i32; let mut _10: i32; + let mut _12: i32; + let mut _13: (i32, i32); + let mut _14: i32; scope 1 { debug a => _1; let _2: i32; @@ -19,13 +22,18 @@ let _6: i32; scope 3 { debug c => _6; + let _11: (i32, (i32, i32), i32); + scope 4 { + debug d => _11; + } } } } bb0: { StorageLive(_1); - _1 = (const 1_i32, const 2_i32); +- _1 = (const 1_i32, const 2_i32); ++ _1 = const (1_i32, 2_i32); StorageLive(_2); StorageLive(_3); StorageLive(_4); @@ -41,7 +49,8 @@ - _2 = Add(move _3, const 3_i32); + _2 = const 6_i32; StorageDead(_3); - _1 = (const 2_i32, const 3_i32); +- _1 = (const 2_i32, const 3_i32); ++ _1 = const (2_i32, 3_i32); StorageLive(_6); StorageLive(_7); StorageLive(_8); @@ -61,11 +70,43 @@ + _6 = const 11_i32; StorageDead(_10); StorageDead(_7); + StorageLive(_11); + StorageLive(_12); +- _12 = _2; ++ _12 = const 6_i32; + StorageLive(_13); +- _13 = _1; ++ _13 = const (2_i32, 3_i32); + StorageLive(_14); +- _14 = _6; +- _11 = (move _12, move _13, move _14); ++ _14 = const 11_i32; ++ _11 = (const 6_i32, const (2_i32, 3_i32), const 11_i32); + StorageDead(_14); + StorageDead(_13); + StorageDead(_12); _0 = const (); + StorageDead(_11); StorageDead(_6); StorageDead(_2); StorageDead(_1); return; } ++ } ++ ++ ALLOC0 (size: 8, align: 4) { ++ 02 00 00 00 03 00 00 00 │ ........ ++ } ++ ++ ALLOC1 (size: 8, align: 4) { ++ 02 00 00 00 03 00 00 00 │ ........ ++ } ++ ++ ALLOC2 (size: 8, align: 4) { ++ 02 00 00 00 03 00 00 00 │ ........ ++ } ++ ++ ALLOC3 (size: 8, align: 4) { ++ 01 00 00 00 02 00 00 00 │ ........ } diff --git a/tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.64bit.diff new file mode 100644 index 0000000000000..f5723cac7d9c8 --- /dev/null +++ b/tests/mir-opt/dataflow-const-prop/tuple.main.DataflowConstProp.64bit.diff @@ -0,0 +1,112 @@ +- // MIR for `main` before DataflowConstProp ++ // MIR for `main` after DataflowConstProp + + fn main() -> () { + let mut _0: (); + let mut _1: (i32, i32); + let mut _3: i32; + let mut _4: i32; + let mut _5: i32; + let mut _7: i32; + let mut _8: i32; + let mut _9: i32; + let mut _10: i32; + let mut _12: i32; + let mut _13: (i32, i32); + let mut _14: i32; + scope 1 { + debug a => _1; + let _2: i32; + scope 2 { + debug b => _2; + let _6: i32; + scope 3 { + debug c => _6; + let _11: (i32, (i32, i32), i32); + scope 4 { + debug d => _11; + } + } + } + } + + bb0: { + StorageLive(_1); +- _1 = (const 1_i32, const 2_i32); ++ _1 = const (1_i32, 2_i32); + StorageLive(_2); + StorageLive(_3); + StorageLive(_4); +- _4 = (_1.0: i32); ++ _4 = const 1_i32; + StorageLive(_5); +- _5 = (_1.1: i32); +- _3 = Add(move _4, move _5); ++ _5 = const 2_i32; ++ _3 = const 3_i32; + StorageDead(_5); + StorageDead(_4); +- _2 = Add(move _3, const 3_i32); ++ _2 = const 6_i32; + StorageDead(_3); +- _1 = (const 2_i32, const 3_i32); ++ _1 = const (2_i32, 3_i32); + StorageLive(_6); + StorageLive(_7); + StorageLive(_8); +- _8 = (_1.0: i32); ++ _8 = const 2_i32; + StorageLive(_9); +- _9 = (_1.1: i32); +- _7 = Add(move _8, move _9); ++ _9 = const 3_i32; ++ _7 = const 5_i32; + StorageDead(_9); + StorageDead(_8); + StorageLive(_10); +- _10 = _2; +- _6 = Add(move _7, move _10); ++ _10 = const 6_i32; ++ _6 = const 11_i32; + StorageDead(_10); + StorageDead(_7); + StorageLive(_11); + StorageLive(_12); +- _12 = _2; ++ _12 = const 6_i32; + StorageLive(_13); +- _13 = _1; ++ _13 = const (2_i32, 3_i32); + StorageLive(_14); +- _14 = _6; +- _11 = (move _12, move _13, move _14); ++ _14 = const 11_i32; ++ _11 = (const 6_i32, const (2_i32, 3_i32), const 11_i32); + StorageDead(_14); + StorageDead(_13); + StorageDead(_12); + _0 = const (); + StorageDead(_11); + StorageDead(_6); + StorageDead(_2); + StorageDead(_1); + return; + } ++ } ++ ++ ALLOC0 (size: 8, align: 4) { ++ 02 00 00 00 03 00 00 00 │ ........ ++ } ++ ++ ALLOC1 (size: 8, align: 4) { ++ 02 00 00 00 03 00 00 00 │ ........ ++ } ++ ++ ALLOC2 (size: 8, align: 4) { ++ 02 00 00 00 03 00 00 00 │ ........ ++ } ++ ++ ALLOC3 (size: 8, align: 4) { ++ 01 00 00 00 02 00 00 00 │ ........ + } + diff --git a/tests/mir-opt/dataflow-const-prop/tuple.rs b/tests/mir-opt/dataflow-const-prop/tuple.rs index c63ce8b140f87..bb706eafe8885 100644 --- a/tests/mir-opt/dataflow-const-prop/tuple.rs +++ b/tests/mir-opt/dataflow-const-prop/tuple.rs @@ -1,5 +1,6 @@ // skip-filecheck // unit-test: DataflowConstProp +// EMIT_MIR_FOR_EACH_BIT_WIDTH // EMIT_MIR tuple.main.DataflowConstProp.diff fn main() { @@ -7,4 +8,6 @@ fn main() { let b = a.0 + a.1 + 3; a = (2, 3); let c = a.0 + a.1 + b; + + let d = (b, a, c); } diff --git a/tests/ui/consts/issue-116186.rs b/tests/ui/consts/issue-116186.rs new file mode 100644 index 0000000000000..a77c38c64dc57 --- /dev/null +++ b/tests/ui/consts/issue-116186.rs @@ -0,0 +1,12 @@ +#![allow(incomplete_features)] +#![feature(generic_const_exprs)] + +fn something(path: [usize; N]) -> impl Clone { + //~^ ERROR cannot find value `N` in this scope + match path { + [] => 0, //~ ERROR cannot pattern-match on an array without a fixed length + _ => 1, + }; +} + +fn main() {} diff --git a/tests/ui/consts/issue-116186.stderr b/tests/ui/consts/issue-116186.stderr new file mode 100644 index 0000000000000..e6eae2d9f55ef --- /dev/null +++ b/tests/ui/consts/issue-116186.stderr @@ -0,0 +1,21 @@ +error[E0425]: cannot find value `N` in this scope + --> $DIR/issue-116186.rs:4:28 + | +LL | fn something(path: [usize; N]) -> impl Clone { + | ^ not found in this scope + | +help: you might be missing a const parameter + | +LL | fn something(path: [usize; N]) -> impl Clone { + | +++++++++++++++++++++ + +error[E0730]: cannot pattern-match on an array without a fixed length + --> $DIR/issue-116186.rs:7:9 + | +LL | [] => 0, + | ^^ + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0425, E0730. +For more information about an error, try `rustc --explain E0425`. diff --git a/triagebot.toml b/triagebot.toml index e3c4233c843b8..dc378d52e9219 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -554,13 +554,9 @@ cc = ["@davidtwco", "@compiler-errors", "@JohnTitor", "@TaKO8Ki"] message = "`rustc_macros::diagnostics` was changed" cc = ["@davidtwco", "@compiler-errors", "@JohnTitor", "@TaKO8Ki"] -[mentions."compiler/rustc_smir"] -message = "This PR changes Stable MIR" -cc = ["@oli-obk", "@celinval", "@spastorino", "@ouz-a"] - [mentions."compiler/stable_mir"] message = "This PR changes Stable MIR" -cc = ["@oli-obk", "@celinval", "@spastorino"] +cc = ["@oli-obk", "@celinval", "@spastorino", "@ouz-a"] [mentions."compiler/rustc_target/src/spec"] message = """