Skip to content

Commit 7e0118c

Browse files
authored
Rollup merge of #136430 - FedericoBruzzone:follow-up-136180, r=oli-obk
Use the type-level constant value `ty::Value` where needed **Follow-up to #136180** ### Summary This PR refactors functions to accept a single type-level constant value `ty::Value` instead of separate `ty::ValTree` and `ty::Ty` parameters: - `valtree_to_const_value`: now takes `ty::Value` - `pretty_print_const_valtree`: now takes `ty::Value` - Uses `pretty_print_const_valtree` for formatting valtrees when `visit_const_operand` - Moves `try_to_raw_bytes` from `ty::Valtree` to `ty::Value` --- r? ``@lukas-code`` ``@oli-obk``
2 parents 2c6c7f8 + 00c61a8 commit 7e0118c

File tree

7 files changed

+79
-78
lines changed

7 files changed

+79
-78
lines changed

compiler/rustc_const_eval/src/const_eval/valtrees.rs

+23-19
Original file line numberDiff line numberDiff line change
@@ -273,59 +273,63 @@ pub(crate) fn eval_to_valtree<'tcx>(
273273
/// Converts a `ValTree` to a `ConstValue`, which is needed after mir
274274
/// construction has finished.
275275
// FIXME(valtrees): Merge `valtree_to_const_value` and `valtree_into_mplace` into one function
276-
// FIXME(valtrees): Accept `ty::Value` instead of `Ty` and `ty::ValTree` separately.
277276
#[instrument(skip(tcx), level = "debug", ret)]
278277
pub fn valtree_to_const_value<'tcx>(
279278
tcx: TyCtxt<'tcx>,
280279
typing_env: ty::TypingEnv<'tcx>,
281-
ty: Ty<'tcx>,
282-
valtree: ty::ValTree<'tcx>,
280+
cv: ty::Value<'tcx>,
283281
) -> mir::ConstValue<'tcx> {
284282
// Basic idea: We directly construct `Scalar` values from trivial `ValTree`s
285283
// (those for constants with type bool, int, uint, float or char).
286284
// For all other types we create an `MPlace` and fill that by walking
287285
// the `ValTree` and using `place_projection` and `place_field` to
288286
// create inner `MPlace`s which are filled recursively.
289-
// FIXME Does this need an example?
290-
match *ty.kind() {
287+
// FIXME: Does this need an example?
288+
match *cv.ty.kind() {
291289
ty::FnDef(..) => {
292-
assert!(valtree.unwrap_branch().is_empty());
290+
assert!(cv.valtree.unwrap_branch().is_empty());
293291
mir::ConstValue::ZeroSized
294292
}
295293
ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char | ty::RawPtr(_, _) => {
296-
match valtree {
294+
match cv.valtree {
297295
ty::ValTree::Leaf(scalar_int) => mir::ConstValue::Scalar(Scalar::Int(scalar_int)),
298296
ty::ValTree::Branch(_) => bug!(
299297
"ValTrees for Bool, Int, Uint, Float, Char or RawPtr should have the form ValTree::Leaf"
300298
),
301299
}
302300
}
303-
ty::Pat(ty, _) => valtree_to_const_value(tcx, typing_env, ty, valtree),
301+
ty::Pat(ty, _) => {
302+
let cv = ty::Value { valtree: cv.valtree, ty };
303+
valtree_to_const_value(tcx, typing_env, cv)
304+
}
304305
ty::Ref(_, inner_ty, _) => {
305306
let mut ecx =
306307
mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, typing_env, CanAccessMutGlobal::No);
307-
let imm = valtree_to_ref(&mut ecx, valtree, inner_ty);
308-
let imm =
309-
ImmTy::from_immediate(imm, tcx.layout_of(typing_env.as_query_input(ty)).unwrap());
308+
let imm = valtree_to_ref(&mut ecx, cv.valtree, inner_ty);
309+
let imm = ImmTy::from_immediate(
310+
imm,
311+
tcx.layout_of(typing_env.as_query_input(cv.ty)).unwrap(),
312+
);
310313
op_to_const(&ecx, &imm.into(), /* for diagnostics */ false)
311314
}
312315
ty::Tuple(_) | ty::Array(_, _) | ty::Adt(..) => {
313-
let layout = tcx.layout_of(typing_env.as_query_input(ty)).unwrap();
316+
let layout = tcx.layout_of(typing_env.as_query_input(cv.ty)).unwrap();
314317
if layout.is_zst() {
315318
// Fast path to avoid some allocations.
316319
return mir::ConstValue::ZeroSized;
317320
}
318321
if layout.backend_repr.is_scalar()
319-
&& (matches!(ty.kind(), ty::Tuple(_))
320-
|| matches!(ty.kind(), ty::Adt(def, _) if def.is_struct()))
322+
&& (matches!(cv.ty.kind(), ty::Tuple(_))
323+
|| matches!(cv.ty.kind(), ty::Adt(def, _) if def.is_struct()))
321324
{
322325
// A Scalar tuple/struct; we can avoid creating an allocation.
323-
let branches = valtree.unwrap_branch();
326+
let branches = cv.valtree.unwrap_branch();
324327
// Find the non-ZST field. (There can be aligned ZST!)
325328
for (i, &inner_valtree) in branches.iter().enumerate() {
326329
let field = layout.field(&LayoutCx::new(tcx, typing_env), i);
327330
if !field.is_zst() {
328-
return valtree_to_const_value(tcx, typing_env, field.ty, inner_valtree);
331+
let cv = ty::Value { valtree: inner_valtree, ty: field.ty };
332+
return valtree_to_const_value(tcx, typing_env, cv);
329333
}
330334
}
331335
bug!("could not find non-ZST field during in {layout:#?}");
@@ -335,9 +339,9 @@ pub fn valtree_to_const_value<'tcx>(
335339
mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, typing_env, CanAccessMutGlobal::No);
336340

337341
// Need to create a place for this valtree.
338-
let place = create_valtree_place(&mut ecx, layout, valtree);
342+
let place = create_valtree_place(&mut ecx, layout, cv.valtree);
339343

340-
valtree_into_mplace(&mut ecx, &place, valtree);
344+
valtree_into_mplace(&mut ecx, &place, cv.valtree);
341345
dump_place(&ecx, &place);
342346
intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &place).unwrap();
343347

@@ -362,7 +366,7 @@ pub fn valtree_to_const_value<'tcx>(
362366
| ty::Slice(_)
363367
| ty::Dynamic(..)
364368
| ty::UnsafeBinder(_) => {
365-
bug!("no ValTree should have been created for type {:?}", ty.kind())
369+
bug!("no ValTree should have been created for type {:?}", cv.ty.kind())
366370
}
367371
}
368372
}

compiler/rustc_const_eval/src/lib.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,8 @@ pub fn provide(providers: &mut Providers) {
4646
};
4747
providers.hooks.try_destructure_mir_constant_for_user_output =
4848
const_eval::try_destructure_mir_constant_for_user_output;
49-
providers.valtree_to_const_val = |tcx, cv| {
50-
const_eval::valtree_to_const_value(
51-
tcx,
52-
ty::TypingEnv::fully_monomorphized(),
53-
cv.ty,
54-
cv.valtree,
55-
)
56-
};
49+
providers.valtree_to_const_val =
50+
|tcx, cv| const_eval::valtree_to_const_value(tcx, ty::TypingEnv::fully_monomorphized(), cv);
5751
providers.check_validity_requirement = |tcx, (init_kind, param_env_and_ty)| {
5852
util::check_validity_requirement(tcx, init_kind, param_env_and_ty)
5953
};

compiler/rustc_middle/src/mir/pretty.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_middle::mir::interpret::{
1212
use rustc_middle::mir::visit::Visitor;
1313
use rustc_middle::mir::*;
1414
use tracing::trace;
15+
use ty::print::PrettyPrinter;
1516

1617
use super::graphviz::write_mir_fn_graphviz;
1718
use crate::mir::interpret::ConstAllocation;
@@ -1439,10 +1440,10 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
14391440
})
14401441
};
14411442

1442-
// FIXME: call pretty_print_const_valtree?
1443-
let fmt_valtree = |valtree: &ty::ValTree<'tcx>| match valtree {
1444-
ty::ValTree::Leaf(leaf) => format!("Leaf({leaf:?})"),
1445-
ty::ValTree::Branch(_) => "Branch(..)".to_string(),
1443+
let fmt_valtree = |cv: &ty::Value<'tcx>| {
1444+
let mut cx = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1445+
cx.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1446+
cx.into_buffer()
14461447
};
14471448

14481449
let val = match const_ {
@@ -1452,7 +1453,7 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
14521453
format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
14531454
}
14541455
ty::ConstKind::Value(cv) => {
1455-
format!("ty::Valtree({})", fmt_valtree(&cv.valtree))
1456+
format!("ty::Valtree({})", fmt_valtree(&cv))
14561457
}
14571458
// No `ty::` prefix since we also use this to represent errors from `mir::Unevaluated`.
14581459
ty::ConstKind::Error(_) => "Error".to_string(),

compiler/rustc_middle/src/ty/consts/valtree.rs

+23-24
Original file line numberDiff line numberDiff line change
@@ -78,30 +78,6 @@ impl<'tcx> ValTree<'tcx> {
7878
Self::Branch(_) => None,
7979
}
8080
}
81-
82-
/// Get the values inside the ValTree as a slice of bytes. This only works for
83-
/// constants with types &str, &[u8], or [u8; _].
84-
pub fn try_to_raw_bytes(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx [u8]> {
85-
match ty.kind() {
86-
ty::Ref(_, inner_ty, _) => match inner_ty.kind() {
87-
// `&str` can be interpreted as raw bytes
88-
ty::Str => {}
89-
// `&[u8]` can be interpreted as raw bytes
90-
ty::Slice(slice_ty) if *slice_ty == tcx.types.u8 => {}
91-
// other `&_` can't be interpreted as raw bytes
92-
_ => return None,
93-
},
94-
// `[u8; N]` can be interpreted as raw bytes
95-
ty::Array(array_ty, _) if *array_ty == tcx.types.u8 => {}
96-
// Otherwise, type cannot be interpreted as raw bytes
97-
_ => return None,
98-
}
99-
100-
Some(
101-
tcx.arena
102-
.alloc_from_iter(self.unwrap_branch().into_iter().map(|v| v.unwrap_leaf().to_u8())),
103-
)
104-
}
10581
}
10682

10783
/// A type-level constant value.
@@ -143,6 +119,29 @@ impl<'tcx> Value<'tcx> {
143119
}
144120
self.valtree.try_to_scalar_int().map(|s| s.to_target_usize(tcx))
145121
}
122+
123+
/// Get the values inside the ValTree as a slice of bytes. This only works for
124+
/// constants with types &str, &[u8], or [u8; _].
125+
pub fn try_to_raw_bytes(self, tcx: TyCtxt<'tcx>) -> Option<&'tcx [u8]> {
126+
match self.ty.kind() {
127+
ty::Ref(_, inner_ty, _) => match inner_ty.kind() {
128+
// `&str` can be interpreted as raw bytes
129+
ty::Str => {}
130+
// `&[u8]` can be interpreted as raw bytes
131+
ty::Slice(slice_ty) if *slice_ty == tcx.types.u8 => {}
132+
// other `&_` can't be interpreted as raw bytes
133+
_ => return None,
134+
},
135+
// `[u8; N]` can be interpreted as raw bytes
136+
ty::Array(array_ty, _) if *array_ty == tcx.types.u8 => {}
137+
// Otherwise, type cannot be interpreted as raw bytes
138+
_ => return None,
139+
}
140+
141+
Some(tcx.arena.alloc_from_iter(
142+
self.valtree.unwrap_branch().into_iter().map(|v| v.unwrap_leaf().to_u8()),
143+
))
144+
}
146145
}
147146

148147
impl<'tcx> rustc_type_ir::inherent::ValueConst<TyCtxt<'tcx>> for Value<'tcx> {

compiler/rustc_middle/src/ty/print/pretty.rs

+22-20
Original file line numberDiff line numberDiff line change
@@ -1487,7 +1487,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
14871487
},
14881488
ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
14891489
ty::ConstKind::Value(cv) => {
1490-
return self.pretty_print_const_valtree(cv.valtree, cv.ty, print_ty);
1490+
return self.pretty_print_const_valtree(cv, print_ty);
14911491
}
14921492

14931493
ty::ConstKind::Bound(debruijn, bound_var) => {
@@ -1787,48 +1787,47 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
17871787
Ok(())
17881788
}
17891789

1790-
// FIXME(valtrees): Accept `ty::Value` instead of `Ty` and `ty::ValTree` separately.
17911790
fn pretty_print_const_valtree(
17921791
&mut self,
1793-
valtree: ty::ValTree<'tcx>,
1794-
ty: Ty<'tcx>,
1792+
cv: ty::Value<'tcx>,
17951793
print_ty: bool,
17961794
) -> Result<(), PrintError> {
17971795
define_scoped_cx!(self);
17981796

17991797
if self.should_print_verbose() {
1800-
p!(write("ValTree({:?}: ", valtree), print(ty), ")");
1798+
p!(write("ValTree({:?}: ", cv.valtree), print(cv.ty), ")");
18011799
return Ok(());
18021800
}
18031801

18041802
let u8_type = self.tcx().types.u8;
1805-
match (valtree, ty.kind()) {
1803+
match (cv.valtree, cv.ty.kind()) {
18061804
(ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
18071805
ty::Slice(t) if *t == u8_type => {
1808-
let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1806+
let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
18091807
bug!(
18101808
"expected to convert valtree {:?} to raw bytes for type {:?}",
1811-
valtree,
1809+
cv.valtree,
18121810
t
18131811
)
18141812
});
18151813
return self.pretty_print_byte_str(bytes);
18161814
}
18171815
ty::Str => {
1818-
let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1819-
bug!("expected to convert valtree to raw bytes for type {:?}", ty)
1816+
let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1817+
bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty)
18201818
});
18211819
p!(write("{:?}", String::from_utf8_lossy(bytes)));
18221820
return Ok(());
18231821
}
18241822
_ => {
1823+
let cv = ty::Value { valtree: cv.valtree, ty: *inner_ty };
18251824
p!("&");
1826-
p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty));
1825+
p!(pretty_print_const_valtree(cv, print_ty));
18271826
return Ok(());
18281827
}
18291828
},
18301829
(ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
1831-
let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1830+
let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
18321831
bug!("expected to convert valtree to raw bytes for type {:?}", t)
18331832
});
18341833
p!("*");
@@ -1837,10 +1836,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
18371836
}
18381837
// Aggregates, printed as array/tuple/struct/variant construction syntax.
18391838
(ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1840-
let contents =
1841-
self.tcx().destructure_const(ty::Const::new_value(self.tcx(), valtree, ty));
1839+
let contents = self.tcx().destructure_const(ty::Const::new_value(
1840+
self.tcx(),
1841+
cv.valtree,
1842+
cv.ty,
1843+
));
18421844
let fields = contents.fields.iter().copied();
1843-
match *ty.kind() {
1845+
match *cv.ty.kind() {
18441846
ty::Array(..) => {
18451847
p!("[", comma_sep(fields), "]");
18461848
}
@@ -1857,7 +1859,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
18571859
write!(this, "unreachable()")?;
18581860
Ok(())
18591861
},
1860-
|this| this.print_type(ty),
1862+
|this| this.print_type(cv.ty),
18611863
": ",
18621864
)?;
18631865
}
@@ -1894,21 +1896,21 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
18941896
return self.pretty_print_const_scalar_int(leaf, *inner_ty, print_ty);
18951897
}
18961898
(ty::ValTree::Leaf(leaf), _) => {
1897-
return self.pretty_print_const_scalar_int(leaf, ty, print_ty);
1899+
return self.pretty_print_const_scalar_int(leaf, cv.ty, print_ty);
18981900
}
18991901
// FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
19001902
// their fields instead of just dumping the memory.
19011903
_ => {}
19021904
}
19031905

19041906
// fallback
1905-
if valtree == ty::ValTree::zst() {
1907+
if cv.valtree == ty::ValTree::zst() {
19061908
p!(write("<ZST>"));
19071909
} else {
1908-
p!(write("{:?}", valtree));
1910+
p!(write("{:?}", cv.valtree));
19091911
}
19101912
if print_ty {
1911-
p!(": ", print(ty));
1913+
p!(": ", print(cv.ty));
19121914
}
19131915
Ok(())
19141916
}

compiler/rustc_middle/src/ty/structural_impls.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ impl<'tcx> fmt::Debug for ty::Const<'tcx> {
170170
bug!("we checked that this is a valtree")
171171
};
172172
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
173-
cx.pretty_print_const_valtree(cv.valtree, cv.ty, /*print_ty*/ true)?;
173+
cx.pretty_print_const_valtree(cv, /*print_ty*/ true)?;
174174
f.write_str(&cx.into_buffer())
175175
});
176176
}

compiler/rustc_symbol_mangling/src/v0.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -649,7 +649,8 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
649649
// HACK(jaic1): hide the `str` type behind a reference
650650
// for the following transformation from valtree to raw bytes
651651
let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty);
652-
let slice = valtree.try_to_raw_bytes(tcx, ref_ty).unwrap_or_else(|| {
652+
let cv = ty::Value { ty: ref_ty, valtree };
653+
let slice = cv.try_to_raw_bytes(tcx).unwrap_or_else(|| {
653654
bug!("expected to get raw bytes from valtree {:?} for type {:}", valtree, ct_ty)
654655
});
655656
let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter");

0 commit comments

Comments
 (0)