Skip to content

Commit 8d4f4cd

Browse files
committed
Reuse the pretty printing architecture for printing of constants
1 parent d85e866 commit 8d4f4cd

File tree

5 files changed

+100
-80
lines changed

5 files changed

+100
-80
lines changed

src/librustc/mir/mod.rs

Lines changed: 10 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ use crate::hir::def_id::DefId;
99
use crate::hir::{self, InlineAsm as HirInlineAsm};
1010
use crate::mir::interpret::{ConstValue, InterpError, Scalar};
1111
use crate::mir::visit::MirVisitable;
12-
use rustc_apfloat::ieee::{Double, Single};
13-
use rustc_apfloat::Float;
1412
use rustc_data_structures::fx::FxHashSet;
1513
use rustc_data_structures::graph::dominators::{dominators, Dominators};
1614
use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
@@ -21,13 +19,13 @@ use rustc_macros::HashStable;
2119
use crate::rustc_serialize::{self as serialize};
2220
use smallvec::SmallVec;
2321
use std::borrow::Cow;
24-
use std::fmt::{self, Debug, Formatter, Write};
22+
use std::fmt::{self, Debug, Formatter, Write, Display};
2523
use std::iter::FusedIterator;
2624
use std::ops::{Index, IndexMut};
2725
use std::slice;
2826
use std::vec::IntoIter;
2927
use std::{iter, mem, option, u32};
30-
use syntax::ast::{self, Name};
28+
use syntax::ast::Name;
3129
use syntax::symbol::{InternedString, Symbol};
3230
use syntax_pos::{Span, DUMMY_SP};
3331
use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
@@ -1670,18 +1668,15 @@ impl<'tcx> TerminatorKind<'tcx> {
16701668
values
16711669
.iter()
16721670
.map(|&u| {
1673-
let mut s = String::new();
1674-
let c = ty::Const {
1671+
(&ty::Const {
16751672
val: ConstValue::Scalar(
16761673
Scalar::Bits {
16771674
bits: u,
16781675
size: size.bytes() as u8,
16791676
}.into(),
16801677
),
16811678
ty: switch_ty,
1682-
};
1683-
fmt_const_val(&mut s, c).unwrap();
1684-
s.into()
1679+
}).to_string().into()
16851680
}).chain(iter::once("otherwise".into()))
16861681
.collect()
16871682
}
@@ -2827,67 +2822,15 @@ newtype_index! {
28272822

28282823
impl<'tcx> Debug for Constant<'tcx> {
28292824
fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2830-
write!(fmt, "const ")?;
2831-
fmt_const_val(fmt, *self.literal)
2832-
}
2833-
}
2834-
/// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2835-
pub fn fmt_const_val(f: &mut impl Write, const_val: ty::Const<'_>) -> fmt::Result {
2836-
use crate::ty::TyKind::*;
2837-
let value = const_val.val;
2838-
let ty = const_val.ty;
2839-
// print some primitives
2840-
if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2841-
match ty.sty {
2842-
Bool if bits == 0 => return write!(f, "false"),
2843-
Bool if bits == 1 => return write!(f, "true"),
2844-
Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2845-
Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2846-
Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2847-
Int(i) => {
2848-
let bit_width = ty::tls::with(|tcx| {
2849-
let ty = tcx.lift_to_global(&ty).unwrap();
2850-
tcx.layout_of(ty::ParamEnv::empty().and(ty))
2851-
.unwrap()
2852-
.size
2853-
.bits()
2854-
});
2855-
let shift = 128 - bit_width;
2856-
return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2857-
}
2858-
Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2859-
_ => {}
2860-
}
2825+
write!(fmt, "{}", self)
28612826
}
2862-
// print function definitions
2863-
if let FnDef(did, _) = ty.sty {
2864-
return write!(f, "{}", def_path_str(did));
2865-
}
2866-
// print string literals
2867-
if let ConstValue::Slice(ptr, len) = value {
2868-
if let Scalar::Ptr(ptr) = ptr {
2869-
if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2870-
return ty::tls::with(|tcx| {
2871-
let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2872-
if let Some(interpret::AllocKind::Memory(alloc)) = alloc {
2873-
assert_eq!(len as usize as u64, len);
2874-
let slice =
2875-
&alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2876-
let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2877-
write!(f, "{:?}", s)
2878-
} else {
2879-
write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2880-
}
2881-
});
2882-
}
2883-
}
2884-
}
2885-
// just raw dump everything else
2886-
write!(f, "{:?} : {}", value, ty)
28872827
}
28882828

2889-
fn def_path_str(def_id: DefId) -> String {
2890-
ty::tls::with(|tcx| tcx.def_path_str(def_id))
2829+
impl<'tcx> Display for Constant<'tcx> {
2830+
fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2831+
write!(fmt, "const ")?;
2832+
write!(fmt, "{}", self.literal)
2833+
}
28912834
}
28922835

28932836
impl<'tcx> graph::DirectedGraph for Mir<'tcx> {

src/librustc/ty/print/pretty.rs

Lines changed: 52 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ use crate::middle::cstore::{ExternCrate, ExternCrateSource};
66
use crate::middle::region;
77
use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
88
use crate::ty::subst::{Kind, Subst, UnpackedKind};
9-
use crate::mir::interpret::ConstValue;
9+
use crate::mir::interpret::{ConstValue, sign_extend, Scalar};
10+
use syntax::ast;
11+
use rustc_apfloat::ieee::{Double, Single};
12+
use rustc_apfloat::Float;
1013
use rustc_target::spec::abi::Abi;
1114
use syntax::symbol::{kw, InternedString};
1215

@@ -1533,12 +1536,54 @@ define_print_and_forward_display! {
15331536
p!(print_def_path(self.def_id, self.substs));
15341537
}
15351538

1536-
&'tcx ty::Const<'tcx> {
1537-
match self.val {
1538-
ConstValue::Unevaluated(..) |
1539-
ConstValue::Infer(..) => p!(write("_")),
1540-
ConstValue::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1541-
_ => p!(write("{:?}", self)),
1539+
ty::Const<'tcx> {
1540+
match (self.val, &self.ty.sty) {
1541+
| (ConstValue::Unevaluated(..), _)
1542+
| (ConstValue::Infer(..), _)
1543+
=> p!(write("_: "), print(self.ty)),
1544+
(ConstValue::Param(ParamConst { name, .. }), _) => p!(write("{}", name)),
1545+
(ConstValue::Scalar(Scalar::Bits { bits: 0, .. }), ty::Bool) => p!(write("false")),
1546+
(ConstValue::Scalar(Scalar::Bits { bits: 1, .. }), ty::Bool) => p!(write("true")),
1547+
(ConstValue::Scalar(Scalar::Bits { bits, .. }), ty::Float(ast::FloatTy::F32)) =>
1548+
p!(write(
1549+
"{}f32",
1550+
Single::from_bits(bits)
1551+
)),
1552+
(ConstValue::Scalar(Scalar::Bits { bits, .. }), ty::Float(ast::FloatTy::F64)) =>
1553+
p!(write(
1554+
"{}f64",
1555+
Double::from_bits(bits)
1556+
)),
1557+
(ConstValue::Scalar(Scalar::Bits { bits, ..}), ty::Uint(ui)) =>
1558+
p!(write("{}{}", bits, ui)),
1559+
(ConstValue::Scalar(Scalar::Bits { bits, ..}), ty::Int(i)) => {
1560+
let size = ty::tls::with(|tcx| {
1561+
let ty = tcx.lift_to_global(&self.ty).unwrap();
1562+
tcx.layout_of(ty::ParamEnv::empty().and(ty))
1563+
.unwrap()
1564+
.size
1565+
});
1566+
p!(write("{}{}", sign_extend(bits, size) as i128, i))
1567+
},
1568+
(ConstValue::Scalar(Scalar::Bits { bits, ..}), ty::Char)
1569+
=> p!(write("{}", ::std::char::from_u32(bits as u32).unwrap())),
1570+
(_, ty::FnDef(did, _)) => p!(write("{}", ty::tls::with(|tcx| tcx.def_path_str(*did)))),
1571+
(ConstValue::Slice(_, 0), ty::Ref(_, &ty::TyS { sty: ty::Str, .. }, _)) =>
1572+
p!(write("\"\"")),
1573+
(
1574+
ConstValue::Slice(Scalar::Ptr(ptr), len),
1575+
ty::Ref(_, &ty::TyS { sty: ty::Str, .. }, _),
1576+
) => {
1577+
ty::tls::with(|tcx| {
1578+
let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
1579+
assert_eq!(len as usize as u64, len);
1580+
let slice =
1581+
&alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
1582+
let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
1583+
Ok(p!(write("{:?}", s)))
1584+
})?;
1585+
},
1586+
_ => p!(write("{:?} : ", self.val), print(self.ty)),
15421587
}
15431588
}
15441589

src/librustc/ty/structural_impls.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,9 @@ CloneTypeFoldableAndLiftImpls! {
295295
(),
296296
bool,
297297
usize,
298+
u32,
299+
crate::ty::BoundVar,
300+
crate::ty::DebruijnIndex,
298301
crate::ty::layout::VariantIdx,
299302
u64,
300303
String,
@@ -311,6 +314,8 @@ CloneTypeFoldableAndLiftImpls! {
311314
::rustc_target::spec::abi::Abi,
312315
crate::mir::Local,
313316
crate::mir::Promoted,
317+
crate::mir::interpret::Scalar,
318+
crate::mir::interpret::Pointer,
314319
crate::traits::Reveal,
315320
crate::ty::adjustment::AutoBorrowMutability,
316321
crate::ty::AdtKind,
@@ -788,6 +793,34 @@ BraceStructLiftImpl! {
788793
}
789794
}
790795

796+
BraceStructLiftImpl! {
797+
impl<'a, 'tcx> Lift<'tcx> for ty::Const<'a> {
798+
type Lifted = ty::Const<'tcx>;
799+
val, ty
800+
}
801+
}
802+
803+
EnumLiftImpl! {
804+
impl<'a, 'tcx> Lift<'tcx> for interpret::ConstValue<'a> {
805+
type Lifted = interpret::ConstValue<'tcx>;
806+
(interpret::ConstValue::Unevaluated)(a, b),
807+
(interpret::ConstValue::Param)(a),
808+
(interpret::ConstValue::Infer)(a),
809+
(interpret::ConstValue::Scalar)(a),
810+
(interpret::ConstValue::Slice)(a, b),
811+
(interpret::ConstValue::ByRef)(a, b),
812+
}
813+
}
814+
815+
EnumLiftImpl! {
816+
impl<'a, 'tcx> Lift<'tcx> for ty::InferConst<'a> {
817+
type Lifted = ty::InferConst<'tcx>;
818+
(ty::InferConst::Var)(a),
819+
(ty::InferConst::Fresh)(a),
820+
(ty::InferConst::Canonical)(a, b),
821+
}
822+
}
823+
791824
impl<'a, 'tcx> Lift<'tcx> for ConstVid<'a> {
792825
type Lifted = ConstVid<'tcx>;
793826
fn lift_to_tcx<'b, 'gcx>(&self, _: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {

src/librustc_mir/hair/pattern/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use crate::const_eval::{const_field, const_variant_index};
1010
use crate::hair::util::UserAnnotatedTyHelpers;
1111
use crate::hair::constant::*;
1212

13-
use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
13+
use rustc::mir::{Field, BorrowKind, Mutability};
1414
use rustc::mir::{UserTypeProjection};
1515
use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
1616
use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, UserType, DefIdTree};
@@ -291,15 +291,15 @@ impl<'tcx> fmt::Display for Pattern<'tcx> {
291291
write!(f, "{}", subpattern)
292292
}
293293
PatternKind::Constant { value } => {
294-
fmt_const_val(f, value)
294+
write!(f, "{}", &value)
295295
}
296296
PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
297-
fmt_const_val(f, lo)?;
297+
write!(f, "{}", &lo)?;
298298
match end {
299299
RangeEnd::Included => write!(f, "..=")?,
300300
RangeEnd::Excluded => write!(f, "..")?,
301301
}
302-
fmt_const_val(f, hi)
302+
write!(f, "{}", &hi)
303303
}
304304
PatternKind::Slice { ref prefix, ref slice, ref suffix } |
305305
PatternKind::Array { ref prefix, ref slice, ref suffix } => {

src/librustdoc/clean/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4136,8 +4136,7 @@ fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
41364136
}
41374137
},
41384138
_ => {
4139-
let mut s = String::new();
4140-
::rustc::mir::fmt_const_val(&mut s, n).expect("fmt_const_val failed");
4139+
let mut s = n.to_string();
41414140
// array lengths are obviously usize
41424141
if s.ends_with("usize") {
41434142
let n = s.len() - "usize".len();

0 commit comments

Comments
 (0)