forked from M-Labs/nac3
1
0
Fork 0
nac3/src/main.rs

318 lines
12 KiB
Rust
Raw Normal View History

extern crate inkwell;
extern crate rustpython_parser;
2020-03-26 19:53:14 +08:00
use rustpython_parser::{ast, parser};
use inkwell::OptimizationLevel;
use inkwell::builder::Builder;
use inkwell::context::Context;
use inkwell::module::Module;
use inkwell::targets::*;
2020-03-26 19:53:14 +08:00
use inkwell::types;
2020-03-27 16:54:49 +08:00
use inkwell::types::BasicType;
use inkwell::values;
use std::error::Error;
2020-03-26 19:53:14 +08:00
use std::fmt;
use std::path::Path;
use std::collections::HashMap;
2020-03-29 13:27:00 +08:00
use std::fs;
2020-03-26 19:53:14 +08:00
#[derive(Debug)]
2020-03-27 16:54:49 +08:00
enum CompileErrorKind {
Unsupported(&'static str),
MissingTypeAnnotation,
2020-03-27 23:47:40 +08:00
UnknownTypeAnnotation,
IncompatibleTypes,
2020-03-29 12:20:40 +08:00
UnboundIdentifier,
2020-03-27 23:47:40 +08:00
Internal(&'static str)
2020-03-27 16:54:49 +08:00
}
impl fmt::Display for CompileErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CompileErrorKind::Unsupported(feature)
2020-03-27 23:47:40 +08:00
=> write!(f, "The following Python feature is not supported by NAC3: {}", feature),
2020-03-27 16:54:49 +08:00
CompileErrorKind::MissingTypeAnnotation
=> write!(f, "Missing type annotation"),
CompileErrorKind::UnknownTypeAnnotation
=> write!(f, "Unknown type annotation"),
CompileErrorKind::IncompatibleTypes
=> write!(f, "Incompatible types"),
2020-03-29 12:20:40 +08:00
CompileErrorKind::UnboundIdentifier
=> write!(f, "Unbound identifier"),
2020-03-27 23:47:40 +08:00
CompileErrorKind::Internal(details)
=> write!(f, "Internal compiler error: {}", details),
2020-03-27 16:54:49 +08:00
}
}
}
#[derive(Debug)]
struct CompileError {
location: ast::Location,
kind: CompileErrorKind,
}
2020-03-26 19:53:14 +08:00
impl fmt::Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2020-03-29 13:27:00 +08:00
write!(f, "{}, at {}", self.kind, self.location)
2020-03-26 19:53:14 +08:00
}
}
impl Error for CompileError {}
type CompileResult<T> = Result<T, CompileError>;
struct CodeGen<'ctx> {
context: &'ctx Context,
module: Module<'ctx>,
2020-03-27 16:54:49 +08:00
builder: Builder<'ctx>,
current_source_location: ast::Location,
namespace: HashMap<String, values::BasicValueEnum<'ctx>>,
}
impl<'ctx> CodeGen<'ctx> {
2020-03-26 19:53:14 +08:00
fn new(context: &'ctx Context) -> CodeGen<'ctx> {
CodeGen {
context,
module: context.create_module("kernel"),
2020-03-27 16:54:49 +08:00
builder: context.create_builder(),
current_source_location: ast::Location::default(),
namespace: HashMap::new(),
2020-03-27 16:54:49 +08:00
}
}
fn set_source_location(&mut self, location: ast::Location) {
self.current_source_location = location;
}
fn compile_error(&self, kind: CompileErrorKind) -> CompileError {
CompileError {
location: self.current_source_location,
kind
2020-03-26 19:53:14 +08:00
}
}
fn get_basic_type(&self, name: &str) -> CompileResult<types::BasicTypeEnum<'ctx>> {
match name {
2020-03-27 16:54:41 +08:00
"bool" => Ok(self.context.bool_type().into()),
2020-03-26 19:53:14 +08:00
"int32" => Ok(self.context.i32_type().into()),
"int64" => Ok(self.context.i64_type().into()),
2020-03-27 16:54:41 +08:00
"float32" => Ok(self.context.f32_type().into()),
"float64" => Ok(self.context.f64_type().into()),
_ => Err(self.compile_error(CompileErrorKind::UnknownTypeAnnotation))
2020-03-26 19:53:14 +08:00
}
}
fn compile_function_def(
&mut self,
name: &str,
args: &ast::Parameters,
body: &[ast::Statement],
decorator_list: &[ast::Expression],
returns: &Option<ast::Expression>,
is_async: bool,
) -> CompileResult<()> {
if is_async {
2020-03-27 16:54:49 +08:00
return Err(self.compile_error(CompileErrorKind::Unsupported("async functions")))
}
for decorator in decorator_list.iter() {
self.set_source_location(decorator.location);
if let ast::ExpressionType::Identifier { name } = &decorator.node {
if name != "kernel" && name != "portable" {
return Err(self.compile_error(CompileErrorKind::Unsupported("custom decorators")))
}
} else {
2020-03-28 15:12:12 +08:00
return Err(self.compile_error(CompileErrorKind::Unsupported("decorator must be an identifier")))
2020-03-27 16:54:49 +08:00
}
2020-03-26 19:53:14 +08:00
}
let args_type = args.args.iter().map(|val| {
2020-03-27 16:54:49 +08:00
self.set_source_location(val.location);
2020-03-26 19:53:14 +08:00
if let Some(annotation) = &val.annotation {
if let ast::ExpressionType::Identifier { name } = &annotation.node {
Ok(self.get_basic_type(&name)?)
} else {
2020-03-28 15:12:12 +08:00
Err(self.compile_error(CompileErrorKind::Unsupported("type annotation must be an identifier")))
2020-03-26 19:53:14 +08:00
}
} else {
2020-03-27 16:54:49 +08:00
Err(self.compile_error(CompileErrorKind::MissingTypeAnnotation))
2020-03-26 19:53:14 +08:00
}
}).collect::<CompileResult<Vec<types::BasicTypeEnum>>>()?;
2020-03-27 16:54:49 +08:00
let return_type = if let Some(returns) = returns {
self.set_source_location(returns.location);
if let ast::ExpressionType::Identifier { name } = &returns.node {
if name == "None" { None } else { Some(self.get_basic_type(name)?) }
} else {
2020-03-28 15:12:12 +08:00
return Err(self.compile_error(CompileErrorKind::Unsupported("type annotation must be an identifier")))
2020-03-27 16:54:49 +08:00
}
} else {
None
2020-03-26 19:53:14 +08:00
};
let fn_type = match return_type {
Some(ty) => ty.fn_type(&args_type, false),
None => self.context.void_type().fn_type(&args_type, false)
};
2020-03-26 19:53:14 +08:00
let function = self.module.add_function(name, fn_type, None);
let basic_block = self.context.append_basic_block(function, "entry");
self.builder.position_at_end(basic_block);
for (n, arg) in args.args.iter().enumerate() {
self.namespace.insert(arg.arg.clone(), function.get_nth_param(n as u32).unwrap());
}
2020-03-27 23:47:40 +08:00
for statement in body.iter() {
self.compile_statement(statement, return_type)?;
2020-03-27 23:47:40 +08:00
}
2020-03-26 19:53:14 +08:00
Ok(())
}
fn compile_expression(
&mut self,
expression: &ast::Expression
) -> CompileResult<values::BasicValueEnum<'ctx>> {
self.set_source_location(expression.location);
match &expression.node {
2020-03-29 12:20:40 +08:00
ast::ExpressionType::Identifier { name } => {
match self.namespace.get(name) {
Some(value) => Ok(*value),
None => Err(self.compile_error(CompileErrorKind::UnboundIdentifier))
}
},
2020-03-29 12:20:40 +08:00
ast::ExpressionType::Binop { a, op, b } => {
let a = self.compile_expression(&a)?;
let b = self.compile_expression(&b)?;
if a.get_type() != b.get_type() {
return Err(self.compile_error(CompileErrorKind::IncompatibleTypes));
}
use ast::Operator::*;
match (op, a, b) {
(Add, values::BasicValueEnum::IntValue(a), values::BasicValueEnum::IntValue(b))
=> Ok(self.builder.build_int_add(a, b, "tmpadd").into()),
(Sub, values::BasicValueEnum::IntValue(a), values::BasicValueEnum::IntValue(b))
=> Ok(self.builder.build_int_sub(a, b, "tmpsub").into()),
(Mult, values::BasicValueEnum::IntValue(a), values::BasicValueEnum::IntValue(b))
=> Ok(self.builder.build_int_mul(a, b, "tmpmul").into()),
(Add, values::BasicValueEnum::FloatValue(a), values::BasicValueEnum::FloatValue(b))
=> Ok(self.builder.build_float_add(a, b, "tmpadd").into()),
(Sub, values::BasicValueEnum::FloatValue(a), values::BasicValueEnum::FloatValue(b))
=> Ok(self.builder.build_float_sub(a, b, "tmpsub").into()),
(Mult, values::BasicValueEnum::FloatValue(a), values::BasicValueEnum::FloatValue(b))
=> Ok(self.builder.build_float_mul(a, b, "tmpmul").into()),
_ => return Err(self.compile_error(CompileErrorKind::Unsupported("unimplemented operation"))),
}
}
_ => return Err(self.compile_error(CompileErrorKind::Unsupported("unimplemented expression"))),
}
}
fn compile_statement(
&mut self,
statement: &ast::Statement,
return_type: Option<types::BasicTypeEnum>
) -> CompileResult<()> {
2020-03-27 16:54:49 +08:00
self.set_source_location(statement.location);
2020-03-26 19:53:14 +08:00
use ast::StatementType::*;
match &statement.node {
2020-03-29 14:10:06 +08:00
Assign { targets, value } => {
let value = self.compile_expression(value)?;
for target in targets.iter() {
self.set_source_location(target.location);
if let ast::ExpressionType::Identifier { name } = &target.node {
if let Some(existing) = self.namespace.insert(name.clone(), value) {
if existing.get_type() != value.get_type() {
return Err(self.compile_error(CompileErrorKind::IncompatibleTypes));
}
}
} else {
return Err(self.compile_error(CompileErrorKind::Unsupported("assignment target must be an identifier")))
}
}
}
Return { value: Some(value) } => {
if let Some(return_type) = return_type {
let value = self.compile_expression(value)?;
if value.get_type() != return_type {
return Err(self.compile_error(CompileErrorKind::IncompatibleTypes));
}
self.builder.build_return(Some(&value));
} else {
return Err(self.compile_error(CompileErrorKind::IncompatibleTypes));
}
},
Return { value: None } => {
if !return_type.is_none() {
return Err(self.compile_error(CompileErrorKind::IncompatibleTypes));
}
self.builder.build_return(None);
},
2020-03-26 19:53:14 +08:00
Pass => (),
2020-03-27 16:54:49 +08:00
_ => return Err(self.compile_error(CompileErrorKind::Unsupported("special statement"))),
2020-03-26 19:53:14 +08:00
}
Ok(())
}
2020-03-27 23:47:40 +08:00
fn compile_toplevel(&mut self, statement: &ast::Statement) -> CompileResult<()> {
self.set_source_location(statement.location);
if let ast::StatementType::FunctionDef {
is_async,
name,
args,
body,
decorator_list,
returns,
} = &statement.node {
self.compile_function_def(name, args, body, decorator_list, returns, *is_async)
} else {
Err(self.compile_error(CompileErrorKind::Internal("top-level is not a function definition")))
}
}
2020-03-26 19:53:14 +08:00
fn output(&self) {
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");
}
}
2020-03-27 16:54:49 +08:00
fn main() {
2020-03-26 19:53:14 +08:00
Target::initialize_all(&InitializationConfig::default());
2020-03-29 13:27:00 +08:00
let program = match fs::read_to_string("test.py") {
Ok(program) => program,
Err(err) => { println!("Cannot open input file: {}", err); return; }
};
let ast = match parser::parse_program(&program) {
2020-03-27 16:54:49 +08:00
Ok(ast) => ast,
2020-03-29 13:27:00 +08:00
Err(err) => { println!("Parse error: {}", err); return; }
2020-03-27 16:54:49 +08:00
};
2020-03-26 19:53:14 +08:00
let context = Context::create();
2020-03-26 19:53:14 +08:00
let mut codegen = CodeGen::new(&context);
2020-03-27 23:47:40 +08:00
match codegen.compile_toplevel(&ast.statements[0]) {
2020-03-27 16:54:49 +08:00
Ok(_) => (),
2020-03-29 13:27:00 +08:00
Err(err) => { println!("Compilation error: {}", err); return; }
2020-03-27 16:54:49 +08:00
}
2020-03-26 19:53:14 +08:00
codegen.output();
}