Skip to main content

xur_bytecode/
display.rs

1//! A readable listing of bytecode, for `xur debug bytecode` and tests.
2
3use std::fmt::Write;
4
5use xur_resolve::Resolutions;
6
7use crate::ir::{Constant, DefRef, Function, InstKind, Reg, Terminator, TypeArg};
8
9/// Lists `function` and the closures it creates.
10pub fn display_function(function: &Function, resolutions: &Resolutions) -> String {
11    let mut out = String::new();
12    write_function(&mut out, function, resolutions, &function.name);
13    out
14}
15
16fn write_function(out: &mut String, function: &Function, resolutions: &Resolutions, name: &str) {
17    let _ = writeln!(
18        out,
19        "fn {name} (captures: {}, params: {}, registers: {})",
20        function.captures, function.params, function.registers
21    );
22    for (i, block) in function.blocks.iter().enumerate() {
23        let _ = writeln!(out, "  bb{i}:");
24        for inst in &block.insts {
25            let _ = writeln!(out, "    {}", inst_text(&inst.kind, resolutions));
26        }
27        let _ = writeln!(out, "    {}", term_text(&block.term));
28    }
29    for (i, closure) in function.closures.iter().enumerate() {
30        let _ = writeln!(out);
31        write_function(out, closure, resolutions, &format!("{name}::closure#{i}"));
32    }
33}
34
35fn regs(regs: &[Reg]) -> String {
36    let regs: Vec<_> = regs.iter().map(|reg| format!("{reg:?}")).collect();
37    regs.join(", ")
38}
39
40fn inst_text(kind: &InstKind, resolutions: &Resolutions) -> String {
41    let path = |def| resolutions.def_path(def);
42    match kind {
43        InstKind::Const { dst, value } => format!("{dst:?} = {}", constant_text(value)),
44        InstKind::Copy { dst, src } => format!("{dst:?} = {src:?}"),
45        InstKind::Def { dst, def } => {
46            let def = match *def {
47                DefRef::Fn(def) => format!("fn {}", path(def)),
48                DefRef::Ctor(def) => format!("ctor {}", path(def)),
49                DefRef::Const(def) => format!("const {}", path(def)),
50                DefRef::Module(def) => format!("module {}", path(def)),
51                DefRef::Native(id) => format!("native #{}", id.0),
52            };
53            format!("{dst:?} = {def}")
54        }
55        InstKind::Unary { dst, op, src } => format!("{dst:?} = {}{src:?}", op.as_str()),
56        InstKind::Binary { dst, op, lhs, rhs } => format!("{dst:?} = {lhs:?} {op} {rhs:?}"),
57        InstKind::Call {
58            dst,
59            callee,
60            args,
61            type_args,
62        } => {
63            let type_args = if type_args.is_empty() {
64                String::new()
65            } else {
66                let args: Vec<_> = type_args
67                    .iter()
68                    .map(|arg| match arg {
69                        TypeArg::Named(name) => name.clone(),
70                        TypeArg::Param(i) => format!("T{i}"),
71                    })
72                    .collect();
73                format!("::<{}>", args.join(", "))
74            };
75            format!("{dst:?} = call {callee:?}{type_args}({})", regs(args))
76        }
77        InstKind::MethodCall {
78            dst,
79            receiver,
80            method,
81            args,
82        } => {
83            format!("{dst:?} = {receiver:?}.{method}({})", regs(args))
84        }
85        InstKind::Field { dst, base, field } => format!("{dst:?} = {base:?}.{field}"),
86        InstKind::Index { dst, base, index } => format!("{dst:?} = {base:?}[{index:?}]"),
87        InstKind::SetIndex { base, index, value } => format!("{base:?}[{index:?}] = {value:?}"),
88        InstKind::Tuple { dst, items } => format!("{dst:?} = ({})", regs(items)),
89        InstKind::List { dst, items } => format!("{dst:?} = [{}]", regs(items)),
90        InstKind::Adt { dst, ctor, fields } => {
91            format!("{dst:?} = {}({})", path(*ctor), regs(fields))
92        }
93        InstKind::Range {
94            dst,
95            start,
96            end,
97            inclusive,
98        } => {
99            let bound = |reg: &Option<Reg>| reg.map(|reg| format!("{reg:?}")).unwrap_or_default();
100            let op = if *inclusive { "..=" } else { ".." };
101            format!("{dst:?} = {}{op}{}", bound(start), bound(end))
102        }
103        InstKind::Closure {
104            dst,
105            function,
106            captures,
107        } => {
108            format!("{dst:?} = closure#{function}({})", regs(captures))
109        }
110        InstKind::IsCtor { dst, value, ctor } => format!("{dst:?} = {value:?} is {}", path(*ctor)),
111        InstKind::IsTuple { dst, value, len } => format!("{dst:?} = {value:?} is tuple of {len}"),
112        InstKind::Project { dst, value, index } => format!("{dst:?} = {value:?}.{index}"),
113        InstKind::IterStart { dst, iterable } => format!("{dst:?} = iter {iterable:?}"),
114        InstKind::CheckType { value, ty } => format!("check {value:?}: {ty}"),
115        InstKind::Error { message } => format!("error {message:?}"),
116    }
117}
118
119fn constant_text(value: &Constant) -> String {
120    match value {
121        Constant::Unit => "()".to_owned(),
122        Constant::Bool(b) => b.to_string(),
123        Constant::Int(i) => i.to_string(),
124        Constant::Float(f) => format!("{f:?}"),
125        Constant::Str(s) => format!("{s:?}"),
126    }
127}
128
129fn term_text(term: &Terminator) -> String {
130    match term {
131        Terminator::Goto(target) => format!("goto {target:?}"),
132        Terminator::Branch {
133            cond,
134            then,
135            otherwise,
136        } => {
137            format!("branch {cond:?} ? {then:?} : {otherwise:?}")
138        }
139        Terminator::Return(value) => format!("return {value:?}"),
140        Terminator::Next {
141            iter,
142            item,
143            body,
144            done,
145        } => {
146            format!("{item:?} = next {iter:?} ? {body:?} : {done:?}")
147        }
148        Terminator::NoMatch => "no match".to_owned(),
149        Terminator::Unreachable => "unreachable".to_owned(),
150    }
151}