Created
February 22, 2024 12:03
-
-
Save lantos1618/3c418f4f74a7a14a3158ac7b3571d007 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn generate_add_func(module: &mut Module) { | |
let mut func = Function::new( | |
Linkage::private(), | |
"add".to_string(), | |
vec![ | |
(Type::Word, Value::Temporary("a".to_string())), | |
(Type::Word, Value::Temporary("b".to_string())), | |
], | |
Some(Type::Word), | |
); | |
func.add_block("start".to_string()); | |
func.assign_instr( | |
Value::Temporary("c".into()), | |
Type::Word, | |
Instr::Add(Value::Temporary("a".into()), Value::Temporary("b".into())), | |
); | |
func.add_instr(Instr::Ret(Some(Value::Temporary("c".into())))); | |
module.add_function(func); | |
} | |
fn generate_main_func<'a>(module: &mut Module<'a>, assignment: &'a AssignmentExpr) { | |
let mut func = Function::new(Linkage::public(), "main".to_string(), Vec::new(), Some(Type::Word)); | |
func.add_block("start".to_string()); | |
func.assign_instr( | |
Value::Temporary(assignment.ident.clone()), | |
assignment.ty.to_qbe_ty(), | |
Instr::Call( | |
"add".to_string(), | |
vec![(Type::Word, Value::Const(1)), (Type::Word, Value::Const(1))], | |
), | |
); | |
// TODO: The example shows a variadic call. We don't have those yet | |
func.add_instr(Instr::Call( | |
"printf".into(), | |
vec![ | |
(Type::Long, Value::Global("fmt".into())), | |
(Type::Word, Value::Temporary("r".into())), | |
], | |
)); | |
func.add_instr(Instr::Ret(Some(Value::Const(0)))); | |
module.add_function(func); | |
} | |
fn generate_data(module: &mut Module) { | |
let items = vec![ | |
(Type::Byte, DataItem::Str("One and one make %d!\\n".into())), | |
(Type::Byte, DataItem::Const(0)), | |
]; | |
let data = DataDef::new(Linkage::private(), "fmt".to_string(), None, items); | |
module.add_data(data); | |
} | |
fn main() { | |
let mut module = Module::new(); | |
let assignment = AssignmentExpr { | |
ident: "a".to_string(), | |
ty: TypeExpr::Int, | |
value: Box::new( | |
Expr::Binary(BinaryExpr { | |
op: BinaryOp::Add, | |
left: Box::new(Expr::Literal(Literal::Integer(1))), | |
right: Box::new(Expr::Literal(Literal::Integer(1))), | |
}), | |
), | |
}; | |
generate_add_func(&mut module); | |
generate_main_func(&mut module, &assignment); | |
generate_data(&mut module); | |
println!("{}", module); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment