use alloc::vec::Vec;
use core::fmt;
use super::Op;
use crate::{SourceSpan, Spanned};
#[derive(Clone, Default)]
pub struct Block {
span: SourceSpan,
body: Vec<Op>,
}
impl Block {
pub fn new(span: SourceSpan, body: Vec<Op>) -> Self {
Self { span, body }
}
pub fn push(&mut self, op: Op) {
self.body.push(op);
}
pub fn len(&self) -> usize {
self.body.len()
}
pub fn is_empty(&self) -> bool {
self.body.is_empty()
}
pub fn iter(&self) -> core::slice::Iter<'_, Op> {
self.body.iter()
}
pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, Op> {
self.body.iter_mut()
}
}
impl fmt::Debug for Block {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(&self.body).finish()
}
}
impl crate::prettier::PrettyPrint for Block {
fn render(&self) -> crate::prettier::Document {
use crate::{ast::Instruction, prettier::*, Span};
let default_body = [Op::Inst(Span::new(self.span, Instruction::Nop))];
let body = match self.body.as_slice() {
[] => default_body.as_slice().iter(),
body => body.iter(),
}
.map(PrettyPrint::render)
.reduce(|acc, doc| acc + nl() + doc);
body.map(|body| indent(4, body)).unwrap_or(Document::Empty)
}
}
impl Spanned for Block {
fn span(&self) -> SourceSpan {
self.span
}
}
impl Eq for Block {}
impl PartialEq for Block {
fn eq(&self, other: &Self) -> bool {
self.body == other.body
}
}