forked from M-Labs/nac3
80 lines
2.3 KiB
Rust
80 lines
2.3 KiB
Rust
|
extern crate inkwell;
|
||
|
extern crate rustpython_parser;
|
||
|
|
||
|
use rustpython_parser::parser;
|
||
|
|
||
|
use inkwell::OptimizationLevel;
|
||
|
use inkwell::builder::Builder;
|
||
|
use inkwell::context::Context;
|
||
|
use inkwell::module::Module;
|
||
|
use inkwell::targets::*;
|
||
|
use inkwell::passes::PassManager;
|
||
|
|
||
|
use std::error::Error;
|
||
|
use std::path::Path;
|
||
|
|
||
|
struct CodeGen<'ctx> {
|
||
|
context: &'ctx Context,
|
||
|
module: Module<'ctx>,
|
||
|
builder: Builder<'ctx>
|
||
|
}
|
||
|
|
||
|
impl<'ctx> CodeGen<'ctx> {
|
||
|
fn compile_sum(&self) {
|
||
|
let i64_type = self.context.i64_type();
|
||
|
let fn_type = i64_type.fn_type(&[i64_type.into(), i64_type.into(), i64_type.into()], false);
|
||
|
let function = self.module.add_function("sum", fn_type, None);
|
||
|
let basic_block = self.context.append_basic_block(function, "entry");
|
||
|
|
||
|
self.builder.position_at_end(basic_block);
|
||
|
|
||
|
let x = function.get_nth_param(0).unwrap().into_int_value();
|
||
|
let y = function.get_nth_param(1).unwrap().into_int_value();
|
||
|
let z = function.get_nth_param(2).unwrap().into_int_value();
|
||
|
|
||
|
let sum = self.builder.build_int_add(x, y, "sum");
|
||
|
let sum = self.builder.build_int_add(sum, z, "sum");
|
||
|
|
||
|
self.builder.build_return(Some(&sum));
|
||
|
|
||
|
Target::initialize_all(&InitializationConfig::default());
|
||
|
|
||
|
//let triple = TargetMachine::get_default_triple();
|
||
|
let triple = TargetTriple::create("riscv32-none-linux-gnu");
|
||
|
let target = Target::from_triple(&triple)
|
||
|
.expect("couldn't create target from target triple");
|
||
|
|
||
|
let target_machine = target
|
||
|
.create_target_machine(
|
||
|
&triple,
|
||
|
"",
|
||
|
"",
|
||
|
OptimizationLevel::Default,
|
||
|
RelocMode::Default,
|
||
|
CodeModel::Default,
|
||
|
)
|
||
|
.expect("couldn't create target machine");
|
||
|
|
||
|
target_machine
|
||
|
.write_to_file(&self.module, FileType::Object, Path::new("test.o"))
|
||
|
.expect("couldn't write module to file");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||
|
let context = Context::create();
|
||
|
let module = context.create_module("sum");
|
||
|
let codegen = CodeGen {
|
||
|
context: &context,
|
||
|
module,
|
||
|
builder: context.create_builder(),
|
||
|
};
|
||
|
codegen.compile_sum();
|
||
|
|
||
|
let x = parser::parse_program("def foo(x: int): print('abc')");
|
||
|
println!("{:?}", x);
|
||
|
|
||
|
Ok(())
|
||
|
}
|