mirror of
https://github.com/Noratrieb/brainfuck.git
synced 2026-01-15 22:05:02 +01:00
things
This commit is contained in:
parent
539d0e0502
commit
7b88c99039
7 changed files with 576 additions and 29 deletions
|
|
@ -1,9 +1,10 @@
|
|||
use crate::parse::Instr;
|
||||
use bumpalo::Bump;
|
||||
|
||||
pub type Ir<'ir> = Vec<IrInstr<'ir>, &'ir Bump>;
|
||||
pub type Ir<'ir> = Vec<Stmt<'ir>, &'ir Bump>;
|
||||
|
||||
pub enum IrInstr<'ir> {
|
||||
#[derive(Debug)]
|
||||
pub enum Stmt<'ir> {
|
||||
Add(u8),
|
||||
Sub(u8),
|
||||
Right(usize),
|
||||
|
|
@ -15,19 +16,65 @@ pub enum IrInstr<'ir> {
|
|||
}
|
||||
|
||||
pub fn optimize<'ir>(alloc: &'ir Bump, instrs: &[Instr<'_>]) -> Ir<'ir> {
|
||||
ast_to_ir(alloc, instrs)
|
||||
let mut ir = ast_to_ir(alloc, instrs);
|
||||
pass_find_set_null(&mut ir);
|
||||
ir
|
||||
}
|
||||
|
||||
fn ast_to_ir<'ir>(alloc: &'ir Bump, ast: &[Instr<'_>]) -> Ir<'ir> {
|
||||
let mut vec = Vec::new_in(alloc);
|
||||
vec.extend(ast.iter().map(|instr| match instr {
|
||||
Instr::Add => IrInstr::Add(1),
|
||||
Instr::Sub => IrInstr::Sub(1),
|
||||
Instr::Right => IrInstr::Right(1),
|
||||
Instr::Left => IrInstr::Left(1),
|
||||
Instr::Out => IrInstr::Out,
|
||||
Instr::In => IrInstr::In,
|
||||
Instr::Loop(body) => IrInstr::Loop(ast_to_ir(alloc, body)),
|
||||
}));
|
||||
vec
|
||||
let mut ir = Vec::new_in(alloc);
|
||||
|
||||
let mut instr_iter = ast.iter();
|
||||
|
||||
let Some(first) = instr_iter.next() else { return ir; };
|
||||
|
||||
let mut last = first;
|
||||
let mut count = 1;
|
||||
|
||||
for next in instr_iter {
|
||||
match last {
|
||||
Instr::Add | Instr::Sub | Instr::Right | Instr::Left if last == next => {
|
||||
count += 1;
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
let new_last = match last {
|
||||
Instr::Add => Stmt::Add(count),
|
||||
Instr::Sub => Stmt::Sub(count),
|
||||
Instr::Right => Stmt::Right(count.into()),
|
||||
Instr::Left => Stmt::Left(count.into()),
|
||||
Instr::Out => Stmt::Out,
|
||||
Instr::In => Stmt::In,
|
||||
Instr::Loop(body) => Stmt::Loop(ast_to_ir(alloc, body)),
|
||||
};
|
||||
ir.push(new_last);
|
||||
last = next;
|
||||
count = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let new_last = match last {
|
||||
Instr::Add => Stmt::Add(count),
|
||||
Instr::Sub => Stmt::Sub(count),
|
||||
Instr::Right => Stmt::Right(count.into()),
|
||||
Instr::Left => Stmt::Left(count.into()),
|
||||
Instr::Out => Stmt::Out,
|
||||
Instr::In => Stmt::In,
|
||||
Instr::Loop(body) => Stmt::Loop(ast_to_ir(alloc, body)),
|
||||
};
|
||||
ir.push(new_last);
|
||||
|
||||
ir
|
||||
}
|
||||
|
||||
fn pass_find_set_null(ir: &mut Ir<'_>) {
|
||||
for stmt in ir {
|
||||
if let Stmt::Loop(body) = stmt {
|
||||
if let [Stmt::Sub(_)] = body.as_slice() {
|
||||
println!("REPLACE");
|
||||
*stmt = Stmt::SetNull;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue