126 lines
2.6 KiB
Rust
126 lines
2.6 KiB
Rust
use std::rc::Rc;
|
|
|
|
use ast::*;
|
|
|
|
pub type TypeName = Rc<String>;
|
|
|
|
pub struct TypeContext {
|
|
|
|
}
|
|
|
|
type InferResult<T> = Result<T, TypeError>;
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct TypeError { }
|
|
|
|
#[derive(Debug, Clone)]
|
|
enum MonoType {
|
|
Var(Rc<String>),
|
|
Const(TConst),
|
|
Arrow(Rc<String>)
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
enum TConst {
|
|
User(Rc<String>),
|
|
Unit,
|
|
Nat,
|
|
Int,
|
|
Float,
|
|
StringT,
|
|
Bool,
|
|
}
|
|
|
|
impl TConst {
|
|
fn user(name: &str) -> TConst {
|
|
TConst::User(Rc::new(name.to_string()))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct PolyType {
|
|
vars: Vec<Rc<String>>,
|
|
ty: MonoType
|
|
}
|
|
|
|
impl TypeContext {
|
|
pub fn new() -> TypeContext {
|
|
TypeContext { }
|
|
}
|
|
|
|
pub fn typecheck(&mut self, ast: &AST) -> Result<String, String> {
|
|
match self.infer_ast(ast) {
|
|
Ok(t) => Ok(format!("{:?}", t)),
|
|
Err(err) => Err(format!("Type error: {:?}", err))
|
|
}
|
|
}
|
|
}
|
|
|
|
impl TypeContext {
|
|
fn infer_ast(&mut self, ast: &AST) -> InferResult<MonoType> {
|
|
let mut output = MonoType::Const(TConst::Unit);
|
|
for statement in ast.0.iter() {
|
|
output = match statement {
|
|
Statement::ExpressionStatement(ref expr) => self.infer_expr(expr)?,
|
|
Statement::Declaration(ref decl) => self.infer_decl(decl)?,
|
|
};
|
|
}
|
|
Ok(output)
|
|
}
|
|
|
|
fn infer_expr(&mut self, expr: &Expression) -> InferResult<MonoType> {
|
|
match expr {
|
|
Expression(expr_type, Some(type_anno)) => unimplemented!(),
|
|
Expression(expr_type, None) => self.infer_expr_type(expr_type)
|
|
}
|
|
}
|
|
|
|
fn infer_decl(&mut self, expr: &Declaration) -> InferResult<MonoType> {
|
|
Ok(MonoType::Const(TConst::user("unimplemented")))
|
|
}
|
|
|
|
fn infer_expr_type(&mut self, expr_type: &ExpressionType) -> InferResult<MonoType> {
|
|
use self::ExpressionType::*;
|
|
Ok(match expr_type {
|
|
NatLiteral(_) => MonoType::Const(TConst::Nat),
|
|
FloatLiteral(_) => MonoType::Const(TConst::Float),
|
|
StringLiteral(_) => MonoType::Const(TConst::StringT),
|
|
BoolLiteral(_) => MonoType::Const(TConst::Bool),
|
|
_ => MonoType::Const(TConst::user("unimplemented"))
|
|
})
|
|
}
|
|
|
|
fn unify(t1: MonoType, t2: MonoType) -> InferResult<MonoType> {
|
|
unimplemented!()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn parse(input: &str) -> AST {
|
|
let tokens: Vec<::tokenizing::Token> = ::tokenizing::tokenize(input);
|
|
let mut parser = ::parsing::Parser::new(tokens);
|
|
parser.parse().unwrap()
|
|
}
|
|
|
|
macro_rules! type_test {
|
|
($input:expr, $correct:expr) => {
|
|
{
|
|
let mut tc = TypeContext::new();
|
|
let ast = parse($input);
|
|
tc.add_symbols(&ast);
|
|
assert_eq!($correct, tc.type_check(&ast).unwrap())
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
fn basic_inference() {
|
|
|
|
}
|
|
}
|