1
1
Fork 0
mirror of https://github.com/azur1s/bobbylisp.git synced 2024-10-16 02:37:40 -05:00

write, read. hello, world!

This commit is contained in:
Natapat Samutpong 2022-03-07 15:29:13 +07:00
parent 722be2628d
commit dccbe7c17c
3 changed files with 22 additions and 4 deletions

View file

@ -17,6 +17,7 @@ impl Codegen {
pub fn gen(&mut self, irs: Vec<IR>) {
self.emit("#include <stdbool.h>\n");
self.emit("#include <iostream>\n");
self.emit("#include <string>\n");
self.emit("int main() {\n");
for ir in irs {
@ -30,6 +31,13 @@ impl Codegen {
IRKind::Define { name, type_hint, value } => {
format!("{} {} = {};\n", type_hint, name, self.gen_ir(value))
},
IRKind::Call { name, args } => {
match name.as_str() {
"write" => { format!("std::cout << {};\n", self.gen_ir(&args[0])) },
"read" => { format!("std::cin >> {};\n", self.gen_ir(&args[0])) },
_ => format!("{}({});\n", name, args.iter().map(|arg| self.gen_ir(arg)).collect::<Vec<_>>().join(", ")),
}
},
IRKind::Value { value } => {
match value {
Value::Int(value) => format!("{}", value),

View file

@ -43,10 +43,19 @@ pub fn expr_to_ir(expr: &Expr) -> IRKind {
let value = expr_to_ir(&value.0);
IRKind::Define { name: name.clone(), type_hint: gen_type_hint(type_hint), value: Box::new(value) }
},
Expr::Call { name, args } => {
let name = match &name.0 {
Expr::Identifier(s) => s.clone(),
_ => panic!("Expected identifier") // TODO: Remove panic and use error handling
};
let args = args.0.iter().map(|arg| expr_to_ir(&arg.0)).collect::<Vec<_>>();
IRKind::Call { name, args }
},
Expr::Int(value) => IRKind::Value { value: Value::Int(*value) },
Expr::Boolean(value) => IRKind::Value { value: Value::Boolean(*value) },
Expr::String(value) => IRKind::Value { value: Value::String(value.clone()) },
Expr::Int(value) => IRKind::Value { value: Value::Int(*value) },
Expr::Boolean(value) => IRKind::Value { value: Value::Boolean(*value) },
Expr::String(value) => IRKind::Value { value: Value::String(value.clone()) },
Expr::Identifier(value) => IRKind::Value { value: Value::Ident(value.clone()) },
_ => { dbg!(expr); todo!() }
}
}

View file

@ -1,3 +1,4 @@
let foo: int = 1;
let baz: bool = true;
let qux: string = "Hello, World";
let qux: string = "Hello, World";
write(qux);