Skip to content

Commit

Permalink
feat(codegen): add & sub
Browse files Browse the repository at this point in the history
  • Loading branch information
MilkeeyCat committed May 25, 2024
1 parent 006f335 commit db7d723
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 10 deletions.
55 changes: 46 additions & 9 deletions src/codegen/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,7 @@ impl<'a> CodeGen<'a> {
text_section: formatdoc!(
"
section .text
global _start
_start:
call main
mov rax, 60
mov rdi, 0
syscall
global main
main:
"
Expand Down Expand Up @@ -110,11 +103,23 @@ impl<'a> CodeGen<'a> {

self.mov(name, right);

return 69;
69
} else {
panic!("Cant assign to non ident");
}
}
BinOp::Add => {
let left = self.expr(expr.left.as_ref());
let right = self.expr(expr.right.as_ref());

self.add(left, right)
}
BinOp::Sub => {
let left = self.expr(expr.left.as_ref());
let right = self.expr(expr.right.as_ref());

self.sub(left, right)
}
_ => panic!("lasjdf"),
}
}
Expand Down Expand Up @@ -162,6 +167,38 @@ impl<'a> CodeGen<'a> {
r
}

fn add(&mut self, r1: usize, r2: usize) -> usize {
writedoc!(
self.text_section,
"
\tadd {}, {}
",
&self.registers[r1].name,
&self.registers[r2].name,
)
.unwrap();

self.free(r2);

r1
}

fn sub(&mut self, r1: usize, r2: usize) -> usize {
writedoc!(
self.text_section,
"
\tsub {}, {}
",
&self.registers[r1].name,
&self.registers[r2].name,
)
.unwrap();

self.free(r2);

r1
}

pub fn compile(&mut self, program: Vec<Stmt>, path: &str) {
let mut file = File::create(path).expect(&format!("Failed to open a file {}", path));

Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn main() {
"
u8 bar;
bar = 69;
bar = 5 + 10 - 12;
"
.to_string(),
);
Expand Down

0 comments on commit db7d723

Please sign in to comment.