This commit is contained in:
2025-05-31 16:52:49 +02:00
parent f98ca8075d
commit 16431b2ea2
3 changed files with 32 additions and 8 deletions

View File

@@ -3,7 +3,7 @@ func main[] : I64
let b: I64 = 1 let b: I64 = 1
while a < 100000 while a < 100000
print(a) print_i64(a)
let temp: I64 = b let temp: I64 = b
b = a + b b = a + b
a = temp a = temp

2
examples/hello.zr Normal file
View File

@@ -0,0 +1,2 @@
func main[] : I64
print("Hello, World!")

View File

@@ -8,14 +8,22 @@ use crate::{
pub struct CodegenX86_64 { pub struct CodegenX86_64 {
output: String, output: String,
data_section: String,
label_counter: usize, label_counter: usize,
data_counter: usize,
} }
impl CodegenX86_64 { impl CodegenX86_64 {
pub fn new_boxed() -> Box<dyn Codegen> { pub fn new_boxed() -> Box<dyn Codegen> {
Box::new(CodegenX86_64 { Box::new(CodegenX86_64 {
output: String::new(), output: String::new(),
label_counter: 0, data_section: String::from(
"section .data
format db \"%ld\\n\\0\"
",
),
label_counter: 1,
data_counter: 1,
}) })
} }
@@ -27,19 +35,19 @@ impl CodegenX86_64 {
impl Codegen for CodegenX86_64 { impl Codegen for CodegenX86_64 {
fn get_output(&self) -> String { fn get_output(&self) -> String {
self.output.clone() format!("{}{}", self.data_section, self.output)
} }
fn emit_prologue(&mut self) -> Result<(), Box<dyn Error>> { fn emit_prologue(&mut self) -> Result<(), Box<dyn Error>> {
writeln!( writeln!(
&mut self.output, &mut self.output,
"section .data "
format db \"%ld\", 10, 0
section .text section .text
extern printf extern printf
extern puts
print equ puts
print: print_i64:
push rbp push rbp
mov rbp, rsp mov rbp, rsp
mov rdi, format mov rdi, format
@@ -203,7 +211,21 @@ print:
Expr::Grouping(expr) => self.compile_expr(env, *expr)?, Expr::Grouping(expr) => self.compile_expr(env, *expr)?,
Expr::Literal(token) => match token.token_type { Expr::Literal(token) => match token.token_type {
TokenType::Number => writeln!(&mut self.output, " mov rax, {}", token.lexeme)?, TokenType::Number => writeln!(&mut self.output, " mov rax, {}", token.lexeme)?,
TokenType::String => todo!(), TokenType::String => {
let value = &token.lexeme[1..token.lexeme.len() - 1];
let charcodes = value
.chars()
.map(|x| format!("{}", x as u8))
.collect::<Vec<String>>()
.join(",");
writeln!(
&mut self.data_section,
" S{} db {},0",
self.data_counter, charcodes
)?;
writeln!(&mut self.output, " mov rax, S{}", self.data_counter)?;
self.data_counter += 1;
}
_ => unreachable!(), _ => unreachable!(),
}, },
Expr::Unary { op, right } => { Expr::Unary { op, right } => {