Skip to content

Commit dd6ddcb

Browse files
committedNov 8, 2024
[StableMIR] A few fixes to pretty printing
Improve identation, and a few other rvalue printing
1 parent e8c698b commit dd6ddcb

File tree

4 files changed

+395
-25
lines changed

4 files changed

+395
-25
lines changed
 

‎compiler/stable_mir/src/mir/pretty.rs

+76-25
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1+
//! Implement methods to pretty print stable MIR body.
12
use std::fmt::Debug;
23
use std::io::Write;
34
use std::{fmt, io, iter};
45

56
use fmt::{Display, Formatter};
67

7-
use super::{AssertMessage, BinOp, BorrowKind, FakeBorrowKind, TerminatorKind};
8+
use super::{AggregateKind, AssertMessage, BinOp, BorrowKind, FakeBorrowKind, TerminatorKind};
89
use crate::mir::{Operand, Place, Rvalue, StatementKind, UnwindAction, VarDebugInfoContents};
9-
use crate::ty::{IndexedVal, MirConst, Ty, TyConst};
10-
use crate::{Body, Mutability, with};
10+
use crate::ty::{AdtKind, IndexedVal, MirConst, Ty, TyConst};
11+
use crate::{Body, CrateDef, Mutability, with};
1112

1213
impl Display for Ty {
1314
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
@@ -23,10 +24,11 @@ impl Debug for Place {
2324

2425
pub(crate) fn function_body<W: Write>(writer: &mut W, body: &Body, name: &str) -> io::Result<()> {
2526
write!(writer, "fn {name}(")?;
26-
body.arg_locals()
27-
.iter()
28-
.enumerate()
29-
.try_for_each(|(index, local)| write!(writer, "_{}: {}", index + 1, local.ty))?;
27+
let mut sep = "";
28+
for (index, local) in body.arg_locals().iter().enumerate() {
29+
write!(writer, "{}_{}: {}", sep, index + 1, local.ty)?;
30+
sep = ", ";
31+
}
3032
write!(writer, ")")?;
3133

3234
let return_local = body.ret_local();
@@ -73,39 +75,40 @@ pub(crate) fn function_body<W: Write>(writer: &mut W, body: &Body, name: &str) -
7375
}
7476

7577
fn pretty_statement<W: Write>(writer: &mut W, statement: &StatementKind) -> io::Result<()> {
78+
const INDENT: &str = " ";
7679
match statement {
7780
StatementKind::Assign(place, rval) => {
78-
write!(writer, " {place:?} = ")?;
81+
write!(writer, "{INDENT}{place:?} = ")?;
7982
pretty_rvalue(writer, rval)?;
8083
writeln!(writer, ";")
8184
}
8285
// FIXME: Add rest of the statements
8386
StatementKind::FakeRead(cause, place) => {
84-
writeln!(writer, "FakeRead({cause:?}, {place:?});")
87+
writeln!(writer, "{INDENT}FakeRead({cause:?}, {place:?});")
8588
}
8689
StatementKind::SetDiscriminant { place, variant_index } => {
87-
writeln!(writer, "discriminant({place:?} = {};", variant_index.to_index())
90+
writeln!(writer, "{INDENT}discriminant({place:?} = {};", variant_index.to_index())
8891
}
8992
StatementKind::Deinit(place) => writeln!(writer, "Deinit({place:?};"),
9093
StatementKind::StorageLive(local) => {
91-
writeln!(writer, "StorageLive(_{local});")
94+
writeln!(writer, "{INDENT}StorageLive(_{local});")
9295
}
9396
StatementKind::StorageDead(local) => {
94-
writeln!(writer, "StorageDead(_{local});")
97+
writeln!(writer, "{INDENT}StorageDead(_{local});")
9598
}
9699
StatementKind::Retag(kind, place) => writeln!(writer, "Retag({kind:?}, {place:?});"),
97100
StatementKind::PlaceMention(place) => {
98-
writeln!(writer, "PlaceMention({place:?};")
101+
writeln!(writer, "{INDENT}PlaceMention({place:?};")
99102
}
100103
StatementKind::ConstEvalCounter => {
101-
writeln!(writer, "ConstEvalCounter;")
104+
writeln!(writer, "{INDENT}ConstEvalCounter;")
102105
}
103-
StatementKind::Nop => writeln!(writer, "nop;"),
106+
StatementKind::Nop => writeln!(writer, "{INDENT}nop;"),
104107
StatementKind::AscribeUserType { .. }
105108
| StatementKind::Coverage(_)
106109
| StatementKind::Intrinsic(_) => {
107110
// FIX-ME: Make them pretty.
108-
writeln!(writer, "{statement:?};")
111+
writeln!(writer, "{INDENT}{statement:?};")
109112
}
110113
}
111114
}
@@ -322,15 +325,11 @@ fn pretty_ty_const(ct: &TyConst) -> String {
322325
fn pretty_rvalue<W: Write>(writer: &mut W, rval: &Rvalue) -> io::Result<()> {
323326
match rval {
324327
Rvalue::AddressOf(mutability, place) => {
325-
write!(writer, "&raw {}(*{:?})", pretty_mut(*mutability), place)
328+
write!(writer, "&raw {} {:?}", pretty_mut(*mutability), place)
326329
}
327330
Rvalue::Aggregate(aggregate_kind, operands) => {
328331
// FIXME: Add pretty_aggregate function that returns a pretty string
329-
write!(writer, "{aggregate_kind:?} (")?;
330-
let mut op_iter = operands.iter();
331-
op_iter.next().map_or(Ok(()), |op| write!(writer, "{}", pretty_operand(op)))?;
332-
op_iter.try_for_each(|op| write!(writer, ", {}", pretty_operand(op)))?;
333-
write!(writer, ")")
332+
pretty_aggregate(writer, aggregate_kind, operands)
334333
}
335334
Rvalue::BinaryOp(bin, op1, op2) => {
336335
write!(writer, "{:?}({}, {})", bin, pretty_operand(op1), pretty_operand(op2))
@@ -360,22 +359,74 @@ fn pretty_rvalue<W: Write>(writer: &mut W, rval: &Rvalue) -> io::Result<()> {
360359
write!(writer, "{kind}{place:?}")
361360
}
362361
Rvalue::Repeat(op, cnst) => {
363-
write!(writer, "{} \" \" {}", pretty_operand(op), pretty_ty_const(cnst))
362+
write!(writer, "[{}; {}]", pretty_operand(op), pretty_ty_const(cnst))
364363
}
365364
Rvalue::ShallowInitBox(_, _) => Ok(()),
366365
Rvalue::ThreadLocalRef(item) => {
367366
write!(writer, "thread_local_ref{item:?}")
368367
}
369368
Rvalue::NullaryOp(nul, ty) => {
370-
write!(writer, "{nul:?} {ty} \" \"")
369+
write!(writer, "{nul:?}::<{ty}>() \" \"")
371370
}
372371
Rvalue::UnaryOp(un, op) => {
373-
write!(writer, "{} \" \" {:?}", pretty_operand(op), un)
372+
write!(writer, "{:?}({})", un, pretty_operand(op))
374373
}
375374
Rvalue::Use(op) => write!(writer, "{}", pretty_operand(op)),
376375
}
377376
}
378377

378+
fn pretty_aggregate<W: Write>(
379+
writer: &mut W,
380+
aggregate_kind: &AggregateKind,
381+
operands: &Vec<Operand>,
382+
) -> io::Result<()> {
383+
let suffix = match aggregate_kind {
384+
AggregateKind::Array(_) => {
385+
write!(writer, "[")?;
386+
"]"
387+
}
388+
AggregateKind::Tuple => {
389+
write!(writer, "(")?;
390+
")"
391+
}
392+
AggregateKind::Adt(def, var, _, _, _) => {
393+
if def.kind() == AdtKind::Enum {
394+
write!(writer, "{}::{}", def.name(), def.variant(*var).unwrap().name())?;
395+
} else {
396+
write!(writer, "{}", def.variant(*var).unwrap().name())?;
397+
}
398+
if operands.is_empty() {
399+
return Ok(());
400+
}
401+
// FIXME: Change this once we have CtorKind in StableMIR.
402+
write!(writer, "(")?;
403+
")"
404+
}
405+
AggregateKind::Closure(def, _) => {
406+
write!(writer, "{{closure@{}}}(", def.span().diagnostic())?;
407+
")"
408+
}
409+
AggregateKind::Coroutine(def, _, _) => {
410+
write!(writer, "{{coroutine@{}}}(", def.span().diagnostic())?;
411+
")"
412+
}
413+
AggregateKind::RawPtr(ty, mutability) => {
414+
write!(
415+
writer,
416+
"*{} {ty} from (",
417+
if *mutability == Mutability::Mut { "mut" } else { "const" }
418+
)?;
419+
")"
420+
}
421+
};
422+
let mut separator = "";
423+
for op in operands {
424+
write!(writer, "{}{}", separator, pretty_operand(op))?;
425+
separator = ", ";
426+
}
427+
write!(writer, "{suffix}")
428+
}
429+
379430
fn pretty_mut(mutability: Mutability) -> &'static str {
380431
match mutability {
381432
Mutability::Not => " ",

‎compiler/stable_mir/src/ty.rs

+8
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,14 @@ impl Span {
271271
pub fn get_lines(&self) -> LineInfo {
272272
with(|c| c.get_lines(self))
273273
}
274+
275+
/// Return the span location to be printed in diagnostic messages.
276+
///
277+
/// This may leak local file paths and should not be used to build artifacts that may be
278+
/// distributed.
279+
pub fn diagnostic(&self) -> String {
280+
with(|c| c.span_to_string(*self))
281+
}
274282
}
275283

276284
#[derive(Clone, Copy, Debug, Serialize)]

‎tests/ui/stable-mir-print/operands.rs

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//@ compile-flags: -Z unpretty=stable-mir --crate-type lib -C panic=abort
2+
//@ check-pass
3+
//@ only-x86_64
4+
//@ needs-unwind unwind edges are different with panic=abort
5+
//! Check how stable mir pretty printer prints different operands and abort strategy.
6+
7+
pub fn operands(val: u8) {
8+
let array = [val; 10];
9+
let first = array[0];
10+
let last = array[10 - 1];
11+
assert_eq!(first, last);
12+
13+
let reference = &first;
14+
let dereferenced = *reference;
15+
assert_eq!(dereferenced, first);
16+
17+
let tuple = (first, last);
18+
let (first_again, _) = tuple;
19+
let first_again_again = tuple.0;
20+
assert_eq!(first_again, first_again_again);
21+
22+
let length = array.len();
23+
let size_of = std::mem::size_of_val(&length);
24+
assert_eq!(length, size_of);
25+
}
26+
27+
pub struct Dummy {
28+
c: char,
29+
i: i32,
30+
}
31+
32+
pub enum Ctors {
33+
Unit,
34+
StructLike { d: Dummy },
35+
TupLike(bool),
36+
}
37+
38+
pub fn more_operands() -> [Ctors; 3] {
39+
let dummy = Dummy { c: 'a', i: i32::MIN };
40+
let unit = Ctors::Unit;
41+
let struct_like = Ctors::StructLike { d: dummy };
42+
let tup_like = Ctors::TupLike(false);
43+
[unit, struct_like, tup_like]
44+
}
45+
46+
pub fn closures(x: bool, z: bool) -> impl FnOnce(bool) -> bool {
47+
move |y: bool| (x ^ y) || z
48+
}
+263
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
// WARNING: This is highly experimental output it's intended for stable-mir developers only.
2+
// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir.
3+
fn operands(_1: u8) -> () {
4+
let mut _0: ();
5+
let _2: [u8; 10];
6+
let _3: u8;
7+
let _4: usize;
8+
let mut _5: usize;
9+
let mut _6: bool;
10+
let _7: u8;
11+
let _8: usize;
12+
let mut _9: (usize, bool);
13+
let mut _10: usize;
14+
let mut _11: bool;
15+
let mut _12: (&u8, &u8);
16+
let mut _13: &u8;
17+
let mut _14: &u8;
18+
let _15: &u8;
19+
let _16: &u8;
20+
let mut _17: bool;
21+
let mut _18: u8;
22+
let mut _19: u8;
23+
let _20: core::panicking::AssertKind;
24+
let _21: !;
25+
let mut _22: Option<Arguments<'_>>;
26+
let _23: &u8;
27+
let _24: u8;
28+
let mut _25: (&u8, &u8);
29+
let mut _26: &u8;
30+
let mut _27: &u8;
31+
let _28: &u8;
32+
let _29: &u8;
33+
let mut _30: bool;
34+
let mut _31: u8;
35+
let mut _32: u8;
36+
let _33: core::panicking::AssertKind;
37+
let _34: !;
38+
let mut _35: Option<Arguments<'_>>;
39+
let _36: (u8, u8);
40+
let _37: u8;
41+
let _38: u8;
42+
let mut _39: (&u8, &u8);
43+
let mut _40: &u8;
44+
let mut _41: &u8;
45+
let _42: &u8;
46+
let _43: &u8;
47+
let mut _44: bool;
48+
let mut _45: u8;
49+
let mut _46: u8;
50+
let _47: core::panicking::AssertKind;
51+
let _48: !;
52+
let mut _49: Option<Arguments<'_>>;
53+
let _50: usize;
54+
let mut _51: &[u8];
55+
let mut _52: &[u8; 10];
56+
let _53: usize;
57+
let _54: &usize;
58+
let mut _55: (&usize, &usize);
59+
let mut _56: &usize;
60+
let mut _57: &usize;
61+
let _58: &usize;
62+
let _59: &usize;
63+
let mut _60: bool;
64+
let mut _61: usize;
65+
let mut _62: usize;
66+
let _63: core::panicking::AssertKind;
67+
let _64: !;
68+
let mut _65: Option<Arguments<'_>>;
69+
debug val => _1;
70+
debug array => _2;
71+
debug first => _3;
72+
debug last => _7;
73+
debug left_val => _15;
74+
debug right_val => _16;
75+
debug kind => _20;
76+
debug reference => _23;
77+
debug dereferenced => _24;
78+
debug left_val => _28;
79+
debug right_val => _29;
80+
debug kind => _33;
81+
debug tuple => _36;
82+
debug first_again => _37;
83+
debug first_again_again => _38;
84+
debug left_val => _42;
85+
debug right_val => _43;
86+
debug kind => _47;
87+
debug length => _50;
88+
debug size_of => _53;
89+
debug left_val => _58;
90+
debug right_val => _59;
91+
debug kind => _63;
92+
bb0: {
93+
_2 = [_1; 10];
94+
_4 = 0_usize;
95+
_5 = 10_usize;
96+
_6 = Lt(_4, _5);
97+
assert(move _6, "index out of bounds: the length is {} but the index is {}", move _5, _4) -> [success: bb1, unwind unreachable];
98+
}
99+
bb1: {
100+
_3 = _2[_4];
101+
_9 = CheckedSub(10_usize, 1_usize);
102+
assert(!move (_9.1: bool), "attempt to compute `{} - {}`, which would overflow", 10_usize, 1_usize) -> [success: bb2, unwind unreachable];
103+
}
104+
bb2: {
105+
_8 = move (_9.0: usize);
106+
_10 = 10_usize;
107+
_11 = Lt(_8, _10);
108+
assert(move _11, "index out of bounds: the length is {} but the index is {}", move _10, _8) -> [success: bb3, unwind unreachable];
109+
}
110+
bb3: {
111+
_7 = _2[_8];
112+
_13 = &_3;
113+
_14 = &_7;
114+
_12 = (move _13, move _14);
115+
_15 = (_12.0: &u8);
116+
_16 = (_12.1: &u8);
117+
_18 = (*_15);
118+
_19 = (*_16);
119+
_17 = Eq(move _18, move _19);
120+
switchInt(move _17) -> [0: bb5, otherwise: bb4];
121+
}
122+
bb4: {
123+
_23 = &_3;
124+
_24 = (*_23);
125+
_26 = &_24;
126+
_27 = &_3;
127+
_25 = (move _26, move _27);
128+
_28 = (_25.0: &u8);
129+
_29 = (_25.1: &u8);
130+
_31 = (*_28);
131+
_32 = (*_29);
132+
_30 = Eq(move _31, move _32);
133+
switchInt(move _30) -> [0: bb7, otherwise: bb6];
134+
}
135+
bb5: {
136+
_20 = core::panicking::AssertKind::Eq;
137+
_22 = std::option::Option::None;
138+
_21 = core::panicking::assert_failed::<u8, u8>(move _20, _15, _16, move _22) -> unwind unreachable;
139+
}
140+
bb6: {
141+
_36 = (_3, _7);
142+
_37 = (_36.0: u8);
143+
_38 = (_36.0: u8);
144+
_40 = &_37;
145+
_41 = &_38;
146+
_39 = (move _40, move _41);
147+
_42 = (_39.0: &u8);
148+
_43 = (_39.1: &u8);
149+
_45 = (*_42);
150+
_46 = (*_43);
151+
_44 = Eq(move _45, move _46);
152+
switchInt(move _44) -> [0: bb9, otherwise: bb8];
153+
}
154+
bb7: {
155+
_33 = core::panicking::AssertKind::Eq;
156+
_35 = std::option::Option::None;
157+
_34 = core::panicking::assert_failed::<u8, u8>(move _33, _28, _29, move _35) -> unwind unreachable;
158+
}
159+
bb8: {
160+
_52 = &_2;
161+
_51 = move _52 as &[u8];
162+
_50 = PtrMetadata(move _51);
163+
_54 = &_50;
164+
_53 = std::mem::size_of_val::<usize>(_54) -> [return: bb10, unwind unreachable];
165+
}
166+
bb9: {
167+
_47 = core::panicking::AssertKind::Eq;
168+
_49 = std::option::Option::None;
169+
_48 = core::panicking::assert_failed::<u8, u8>(move _47, _42, _43, move _49) -> unwind unreachable;
170+
}
171+
bb10: {
172+
_56 = &_50;
173+
_57 = &_53;
174+
_55 = (move _56, move _57);
175+
_58 = (_55.0: &usize);
176+
_59 = (_55.1: &usize);
177+
_61 = (*_58);
178+
_62 = (*_59);
179+
_60 = Eq(move _61, move _62);
180+
switchInt(move _60) -> [0: bb12, otherwise: bb11];
181+
}
182+
bb11: {
183+
return;
184+
}
185+
bb12: {
186+
_63 = core::panicking::AssertKind::Eq;
187+
_65 = std::option::Option::None;
188+
_64 = core::panicking::assert_failed::<usize, usize>(move _63, _58, _59, move _65) -> unwind unreachable;
189+
}
190+
}
191+
fn operands::{constant#0}() -> usize {
192+
let mut _0: usize;
193+
bb0: {
194+
_0 = 10_usize;
195+
return;
196+
}
197+
}
198+
fn more_operands() -> [Ctors; 3] {
199+
let mut _0: [Ctors; 3];
200+
let _1: Dummy;
201+
let _2: Ctors;
202+
let _3: Ctors;
203+
let _4: Ctors;
204+
debug dummy => _1;
205+
debug unit => _2;
206+
debug struct_like => _3;
207+
debug tup_like => _4;
208+
bb0: {
209+
_1 = Dummy('a', core::num::<impl i32>::MIN);
210+
_2 = Ctors::Unit;
211+
_3 = Ctors::StructLike(move _1);
212+
_4 = Ctors::TupLike(false);
213+
_0 = [move _2, move _3, move _4];
214+
return;
215+
}
216+
}
217+
fn more_operands::{constant#0}() -> usize {
218+
let mut _0: usize;
219+
bb0: {
220+
_0 = 3_usize;
221+
return;
222+
}
223+
}
224+
fn closures(_1: bool, _2: bool) -> {closure@$DIR/operands.rs:47:5: 47:19} {
225+
let mut _0: {closure@$DIR/operands.rs:47:5: 47:19};
226+
debug x => _1;
227+
debug z => _2;
228+
bb0: {
229+
_0 = {closure@$DIR/operands.rs:47:5: 47:19}(_1, _2);
230+
return;
231+
}
232+
}
233+
fn closures::{closure#0}(_1: {closure@$DIR/operands.rs:47:5: 47:19}, _2: bool) -> bool {
234+
let mut _0: bool;
235+
let mut _3: bool;
236+
let mut _4: bool;
237+
debug y => _2;
238+
debug x => (_1.0: bool);
239+
debug z => (_1.1: bool);
240+
bb0: {
241+
_4 = (_1.0: bool);
242+
_3 = BitXor(move _4, _2);
243+
switchInt(move _3) -> [0: bb2, otherwise: bb1];
244+
}
245+
bb1: {
246+
_0 = true;
247+
goto -> bb3;
248+
}
249+
bb2: {
250+
_0 = (_1.1: bool);
251+
goto -> bb3;
252+
}
253+
bb3: {
254+
return;
255+
}
256+
}
257+
fn Ctors::TupLike(_1: bool) -> Ctors {
258+
let mut _0: Ctors;
259+
bb0: {
260+
_0 = Ctors::TupLike(move _1);
261+
return;
262+
}
263+
}

0 commit comments

Comments
 (0)
Please sign in to comment.