This repository has been archived on 2024-06-24. You can view files and clone it, but cannot push or open issues or pull requests.
huia/huia-compiler/src/block.rs

104 lines
2 KiB
Rust

use crate::context::Context;
use crate::env::Env;
use crate::ir::IR;
use crate::stable::StringIdx;
use crate::ty::TyIdx;
use std::slice::IterMut;
/// A basic block.
///
/// A basic block is a collection of
#[derive(Debug, Default, PartialEq, Clone)]
pub struct Block {
env: Env,
ir: Vec<IR>,
}
impl Block {
/// Perform IR-wise improvement.
///
/// See `IR.improve` for more information.
pub fn improve_ir<F: Fn(&mut IR, &mut Context)>(
&mut self,
mut context: &mut Context,
improver: F,
) {
for ir in self.ir.iter_mut() {
improver(ir, &mut context);
}
}
/// Consumes the block and returns the IR data.
pub fn ir(self) -> Vec<IR> {
self.ir
}
pub fn ir_ref(&self) -> Vec<&IR> {
self.ir.iter().collect()
}
pub fn is_empty(&self) -> bool {
self.ir.is_empty()
}
pub fn iter_mut(&mut self) -> IterMut<IR> {
self.ir.iter_mut()
}
pub fn len(&self) -> usize {
self.ir.len()
}
pub fn new(env: Env) -> Block {
Block {
env,
ir: Vec::default(),
}
}
pub fn peek(&self) -> Option<&IR> {
let len = self.ir.len();
self.ir.get(len - 1)
}
pub fn pop(&mut self) -> Option<IR> {
self.ir.pop()
}
pub fn push(&mut self, ir: IR) {
self.ir.push(ir);
}
pub fn env(&self) -> &Env {
&self.env
}
pub fn env_get(&self, name: StringIdx) -> Option<&TyIdx> {
self.env.get(name)
}
pub fn env_set(&mut self, name: StringIdx, ty: TyIdx) {
self.env.set(name, ty)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct BlockIdx(usize);
impl From<usize> for BlockIdx {
fn from(i: usize) -> BlockIdx {
BlockIdx(i)
}
}
impl From<BlockIdx> for usize {
fn from(i: BlockIdx) -> usize {
i.0
}
}
impl From<&BlockIdx> for usize {
fn from(i: &BlockIdx) -> usize {
i.0
}
}