Skip to content

Commit e67fc38

Browse files
committed
Add CodeObject::display_expand_codeobjects
1 parent 2860513 commit e67fc38

File tree

1 file changed

+42
-7
lines changed

1 file changed

+42
-7
lines changed

bytecode/src/bytecode.rs

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -348,26 +348,54 @@ impl CodeObject {
348348
}
349349
})
350350
}
351-
}
352351

353-
impl fmt::Display for CodeObject {
354-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
352+
fn display_inner(
353+
&self,
354+
f: &mut fmt::Formatter,
355+
expand_codeobjects: bool,
356+
level: usize,
357+
) -> fmt::Result {
355358
let label_targets: HashSet<&usize> = self.label_map.values().collect();
356359
for (offset, instruction) in self.instructions.iter().enumerate() {
357360
let arrow = if label_targets.contains(&offset) {
358361
">>"
359362
} else {
360363
" "
361364
};
362-
write!(f, " {} {:5} ", arrow, offset)?;
363-
instruction.fmt_dis(f, &self.label_map)?;
365+
for _ in 0..level {
366+
write!(f, " ")?;
367+
}
368+
write!(f, "{} {:5} ", arrow, offset)?;
369+
instruction.fmt_dis(f, &self.label_map, expand_codeobjects, level)?;
364370
}
365371
Ok(())
366372
}
373+
374+
pub fn display_expand_codeobjects<'a>(&'a self) -> impl fmt::Display + 'a {
375+
struct Display<'a>(&'a CodeObject);
376+
impl fmt::Display for Display<'_> {
377+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378+
self.0.display_inner(f, true, 1)
379+
}
380+
}
381+
Display(self)
382+
}
383+
}
384+
385+
impl fmt::Display for CodeObject {
386+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
387+
self.display_inner(f, false, 1)
388+
}
367389
}
368390

369391
impl Instruction {
370-
fn fmt_dis(&self, f: &mut fmt::Formatter, label_map: &HashMap<Label, usize>) -> fmt::Result {
392+
fn fmt_dis(
393+
&self,
394+
f: &mut fmt::Formatter,
395+
label_map: &HashMap<Label, usize>,
396+
expand_codeobjects: bool,
397+
level: usize,
398+
) -> fmt::Result {
371399
macro_rules! w {
372400
($variant:ident) => {
373401
write!(f, "{:20}\n", stringify!($variant))
@@ -410,7 +438,14 @@ impl Instruction {
410438
DeleteSubscript => w!(DeleteSubscript),
411439
StoreAttr { name } => w!(StoreAttr, name),
412440
DeleteAttr { name } => w!(DeleteAttr, name),
413-
LoadConst { value } => w!(LoadConst, value),
441+
LoadConst { value } => match value {
442+
Constant::Code { code } if expand_codeobjects => {
443+
writeln!(f, "LoadConst ({:?}):", code)?;
444+
code.display_inner(f, true, level + 1)?;
445+
Ok(())
446+
}
447+
_ => w!(LoadConst, value),
448+
},
414449
UnaryOperation { op } => w!(UnaryOperation, format!("{:?}", op)),
415450
BinaryOperation { op, inplace } => w!(BinaryOperation, format!("{:?}", op), inplace),
416451
LoadAttr { name } => w!(LoadAttr, name),

0 commit comments

Comments
 (0)