use super::ast::*;
use super::lex::{Loc, Res, err};
use std::collections::HashMap;
use std::sync::Arc as Rc;
pub const NO_COV: u32 = u32::MAX;
struct Switch {
cases: Vec<(u64, u64, usize)>,
default: Option<usize>,
}
struct Lower<'a> {
prog: &'a mut Program,
fid: u32,
blocks: Vec<Block>,
done: Vec<bool>,
cur: usize,
breaks: Vec<usize>,
conts: Vec<usize>,
labels: HashMap<Rc<str>, usize>,
switches: Vec<Switch>,
}
pub fn lower(prog: &mut Program, fid: u32, body: &Stmt) -> Res<Body> {
let mut l = Lower {
prog,
fid,
blocks: Vec::new(),
done: Vec::new(),
cur: 0,
breaks: Vec::new(),
conts: Vec::new(),
labels: HashMap::new(),
switches: Vec::new(),
};
l.cur = l.new_block();
l.stmt(body)?;
let cur = l.cur;
l.finish(cur, Term::Ret(None), body.loc, false);
let blocks = l.blocks;
let mut live = vec![false; blocks.len()];
let mut stack = vec![0usize];
while let Some(b) = stack.pop() {
if std::mem::replace(&mut live[b], true) {
continue;
}
match &blocks[b].term {
Term::Jump(t) => stack.push(*t),
Term::Br(c, t, e) => match const_truth(c) {
Some(true) => stack.push(*t),
Some(false) => stack.push(*e),
None => stack.extend([*t, *e]),
},
Term::Switch(_, cases, default) => {
stack.extend(cases.iter().map(|c| c.2));
stack.push(*default);
}
Term::Ret(_) | Term::Unreachable => {}
}
}
prog.cov_dead.resize(prog.ncov as usize, false);
for (b, blk) in blocks.iter().enumerate() {
if live[b] {
continue;
}
for c in blk.ops.iter().map(|o| o.cov).chain([blk.term_cov]) {
if c != NO_COV {
prog.cov_dead[c as usize] = true;
}
}
}
Ok(Body { blocks })
}
fn const_truth(e: &Expr) -> Option<bool> {
match &e.kind {
EK::Const(v) => Some(*v != 0),
EK::LogNot(a) => const_truth(a).map(|v| !v),
EK::LogAnd(a, b) => match (const_truth(a), const_truth(b)) {
(Some(false), _) => Some(false),
(Some(true), v) => v,
_ => None,
},
EK::LogOr(a, b) => match (const_truth(a), const_truth(b)) {
(Some(true), _) => Some(true),
(Some(false), v) => v,
_ => None,
},
_ => None,
}
}
impl Lower<'_> {
fn new_block(&mut self) -> usize {
self.blocks.push(Block {
ops: Vec::new(),
term: Term::Unreachable,
term_cov: NO_COV,
term_loc: Loc::default(),
});
self.done.push(false);
self.blocks.len() - 1
}
fn cov(&mut self, loc: Loc) -> u32 {
let id = self.prog.ncov;
self.prog.ncov += 1;
self.prog.cov_info.push((self.fid, loc));
id
}
fn finish(&mut self, b: usize, term: Term, loc: Loc, counted: bool) {
if self.done[b] {
return;
}
self.done[b] = true;
let cov = if counted { self.cov(loc) } else { NO_COV };
let blk = &mut self.blocks[b];
blk.term = term;
blk.term_cov = cov;
blk.term_loc = loc;
}
fn goto(&mut self, target: usize, next: usize, loc: Loc) {
let cur = self.cur;
self.finish(cur, Term::Jump(target), loc, false);
self.cur = next;
}
fn label(&mut self, name: &Rc<str>) -> usize {
if let Some(&b) = self.labels.get(name) {
return b;
}
let b = self.new_block();
self.labels.insert(name.clone(), b);
b
}
fn op(&mut self, kind: OpKind, loc: Loc) {
let cov = self.cov(loc);
self.blocks[self.cur].ops.push(Op { kind, cov, loc });
}
fn stmt(&mut self, s: &Stmt) -> Res<()> {
let loc = s.loc;
match &s.kind {
SK::Empty => {}
SK::Expr(e) => self.op(OpKind::Eval(e.clone()), loc),
SK::Init { var, zero, items } => self.op(
OpKind::Init {
var: *var,
zero: *zero,
items: items.clone(),
},
loc,
),
SK::Block(v) => {
for s in v {
self.stmt(s)?;
}
}
SK::If(c, t, e) => {
let (bt, be, end) = (self.new_block(), self.new_block(), self.new_block());
let cur = self.cur;
self.finish(cur, Term::Br(c.clone(), bt, be), loc, true);
self.cur = bt;
self.stmt(t)?;
self.goto(end, be, loc);
if let Some(e) = e {
self.stmt(e)?;
}
self.goto(end, end, loc);
}
SK::While(c, body) => {
let (head, bb, end) = (self.new_block(), self.new_block(), self.new_block());
self.goto(head, head, loc);
self.finish(head, Term::Br(c.clone(), bb, end), loc, true);
self.cur = bb;
self.breaks.push(end);
self.conts.push(head);
self.stmt(body)?;
self.breaks.pop();
self.conts.pop();
self.goto(head, end, loc);
}
SK::DoWhile(body, c) => {
let (bb, cond, end) = (self.new_block(), self.new_block(), self.new_block());
self.goto(bb, bb, loc);
self.breaks.push(end);
self.conts.push(cond);
self.stmt(body)?;
self.breaks.pop();
self.conts.pop();
self.goto(cond, cond, loc);
self.finish(cond, Term::Br(c.clone(), bb, end), c.loc, true);
self.cur = end;
}
SK::For(init, c, step, body) => {
if let Some(i) = init {
self.stmt(i)?;
}
let (head, bb, st, end) = (self.new_block(), self.new_block(), self.new_block(), self.new_block());
self.goto(head, head, loc);
match c {
Some(c) => self.finish(head, Term::Br(c.clone(), bb, end), loc, true),
None => self.finish(head, Term::Jump(bb), loc, false),
}
self.cur = bb;
self.breaks.push(end);
self.conts.push(st);
self.stmt(body)?;
self.breaks.pop();
self.conts.pop();
self.goto(st, st, loc);
if let Some(e) = step {
self.op(OpKind::Eval(e.clone()), e.loc);
}
self.goto(head, end, loc);
}
SK::Switch(e, body) => {
let head = self.cur;
let end = self.new_block();
self.cur = self.new_block();
self.switches.push(Switch {
cases: Vec::new(),
default: None,
});
self.breaks.push(end);
self.stmt(body)?;
self.breaks.pop();
let sw = self.switches.pop().unwrap();
self.goto(end, end, loc);
self.finish(
head,
Term::Switch(e.clone(), sw.cases, sw.default.unwrap_or(end)),
loc,
true,
);
}
SK::Case(..) | SK::Default => {
let b = self.new_block();
self.goto(b, b, loc);
let Some(sw) = self.switches.last_mut() else {
return err(loc, "case label outside switch");
};
match &s.kind {
SK::Case(lo, hi) => sw.cases.push((*lo, *hi, b)),
_ => sw.default = Some(b),
}
}
SK::Break => {
let Some(&t) = self.breaks.last() else {
return err(loc, "break outside loop or switch");
};
let n = self.new_block();
self.goto(t, n, loc);
}
SK::Continue => {
let Some(&t) = self.conts.last() else {
return err(loc, "continue outside loop");
};
let n = self.new_block();
self.goto(t, n, loc);
}
SK::Return(e) => {
let cur = self.cur;
self.finish(cur, Term::Ret(e.clone()), loc, true);
self.cur = self.new_block();
}
SK::Goto(name) => {
let t = self.label(name);
let n = self.new_block();
self.goto(t, n, loc);
}
SK::Label(name) => {
let b = self.label(name);
self.goto(b, b, loc);
}
}
Ok(())
}
}