schala/schala-lang/src/typechecking.rs

494 lines
14 KiB
Rust
Raw Normal View History

2018-06-03 02:27:52 -07:00
use std::cell::RefCell;
2018-02-21 02:31:28 -08:00
use std::rc::Rc;
2018-06-03 23:25:22 -07:00
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
2018-06-03 02:20:14 -07:00
/*
2018-05-17 00:36:51 -07:00
use std::collections::hash_set::Union;
use std::iter::Iterator;
2018-03-03 11:52:07 -08:00
use itertools::Itertools;
2018-05-27 02:44:06 -07:00
*/
2018-03-03 11:52:07 -08:00
2018-06-04 19:25:40 -07:00
use ast;
2018-05-29 00:09:12 -07:00
use util::StateStack;
2018-07-13 20:04:52 -07:00
use symbol_table::{SymbolSpec, SymbolTable};
2018-02-21 02:31:28 -08:00
2018-05-27 02:44:06 -07:00
pub type TypeName = Rc<String>;
type TypeResult<T> = Result<T, String>;
2018-05-29 00:57:27 -07:00
#[derive(Debug, PartialEq, Clone)]
2018-05-27 02:44:06 -07:00
enum Type {
Const(TConst),
Var(TypeName),
Func(Vec<Type>),
}
2018-05-29 00:57:27 -07:00
#[derive(Debug, PartialEq, Clone)]
2018-05-27 02:44:06 -07:00
enum TConst {
Unit,
Nat,
StringT,
Custom(String)
}
#[derive(Debug, PartialEq, Clone)]
struct Scheme {
names: Vec<TypeName>,
ty: Type,
}
2018-06-03 23:25:22 -07:00
impl fmt::Display for Scheme {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "∀{:?} . {:?}", self.names, self.ty)
}
}
#[derive(Debug, PartialEq, Clone)]
struct Substitution(HashMap<TypeName, Type>);
2018-06-03 02:20:14 -07:00
impl Substitution {
fn empty() -> Substitution {
Substitution(HashMap::new())
}
}
#[derive(Debug, PartialEq, Clone)]
struct TypeEnv(HashMap<TypeName, Scheme>);
2018-06-03 02:20:14 -07:00
impl TypeEnv {
fn default() -> TypeEnv {
TypeEnv(HashMap::new())
}
fn populate_from_symbols(&mut self, symbol_table: &SymbolTable) {
for (name, symbol) in symbol_table.values.iter() {
if let SymbolSpec::Func(ref type_names) = symbol.spec {
let mut ch: char = 'a';
let mut names = vec![];
for _ in type_names.iter() {
names.push(Rc::new(format!("{}", ch)));
ch = ((ch as u8) + 1) as char;
}
let sigma = Scheme {
names: names.clone(),
ty: Type::Func(names.into_iter().map(|n| Type::Var(n)).collect())
};
self.0.insert(name.clone(), sigma);
}
}
}
2018-06-03 02:20:14 -07:00
}
2018-05-29 00:09:12 -07:00
pub struct TypeContext<'a> {
2018-06-03 02:20:14 -07:00
values: StateStack<'a, TypeName, Type>,
2018-06-03 02:27:52 -07:00
symbol_table_handle: Rc<RefCell<SymbolTable>>,
2018-06-03 02:20:14 -07:00
global_env: TypeEnv
2018-05-29 00:09:12 -07:00
}
2018-05-20 23:05:41 -07:00
2018-05-29 00:09:12 -07:00
impl<'a> TypeContext<'a> {
2018-06-03 02:27:52 -07:00
pub fn new(symbol_table_handle: Rc<RefCell<SymbolTable>>) -> TypeContext<'static> {
TypeContext { values: StateStack::new(None), global_env: TypeEnv::default(), symbol_table_handle }
2018-05-20 23:05:41 -07:00
}
2018-05-21 03:09:38 -07:00
pub fn debug_types(&self) -> String {
2018-06-03 23:25:22 -07:00
let mut output = format!("Type environment\n");
for (name, scheme) in &self.global_env.0 {
write!(output, "{} -> {}\n", name, scheme).unwrap();
}
output
2018-05-21 03:09:38 -07:00
}
2018-05-20 23:05:41 -07:00
2018-06-04 19:25:40 -07:00
pub fn type_check_ast(&mut self, input: &ast::AST) -> Result<String, String> {
let ref symbol_table = self.symbol_table_handle.borrow();
self.global_env.populate_from_symbols(symbol_table);
let output = self.global_env.infer_block(&input.0)?;
2018-05-27 02:44:06 -07:00
Ok(format!("{:?}", output))
}
}
2018-06-03 02:20:14 -07:00
impl TypeEnv {
fn instantiate(&mut self, sigma: Scheme) -> Type {
match sigma {
Scheme { ty, .. } => ty,
}
}
fn generate(&mut self, ty: Type) -> Scheme {
Scheme {
names: vec![], //TODO incomplete
ty
}
}
2018-06-04 19:25:40 -07:00
fn infer_block(&mut self, block: &Vec<ast::Statement>) -> TypeResult<Type> {
2018-05-27 02:44:06 -07:00
let mut output = Type::Const(TConst::Unit);
for statement in block {
output = self.infer_statement(statement)?;
}
Ok(output)
}
2018-06-04 19:25:40 -07:00
fn infer_statement(&mut self, statement: &ast::Statement) -> TypeResult<Type> {
2018-05-27 02:44:06 -07:00
match statement {
2018-06-04 19:25:40 -07:00
ast::Statement::ExpressionStatement(expr) => self.infer_expr(expr),
ast::Statement::Declaration(decl) => self.infer_decl(decl)
2018-05-27 02:44:06 -07:00
}
}
2018-06-04 19:25:40 -07:00
fn infer_decl(&mut self, decl: &ast::Declaration) -> TypeResult<Type> {
use ast::Declaration::*;
2018-05-29 00:09:12 -07:00
match decl {
Binding { name, expr, .. } => {
2018-05-29 00:21:03 -07:00
let ty = self.infer_expr(expr)?;
2018-06-03 02:20:14 -07:00
let sigma = self.generate(ty);
self.0.insert(name.clone(), sigma);
2018-05-29 00:09:12 -07:00
},
_ => (),
}
2018-05-27 02:44:06 -07:00
Ok(Type::Const(TConst::Unit))
}
2018-06-04 19:25:40 -07:00
fn infer_expr(&mut self, expr: &ast::Expression) -> TypeResult<Type> {
2018-05-28 23:39:58 -07:00
match expr {
2018-06-04 19:25:40 -07:00
ast::Expression(expr, Some(anno)) => {
2018-05-28 23:39:58 -07:00
self.infer_exprtype(expr)
},
2018-06-04 19:25:40 -07:00
ast::Expression(expr, None) => {
2018-05-28 23:39:58 -07:00
self.infer_exprtype(expr)
}
}
}
2018-06-04 19:25:40 -07:00
fn infer_exprtype(&mut self, expr: &ast::ExpressionType) -> TypeResult<Type> {
2018-05-28 23:39:58 -07:00
use self::TConst::*;
2018-06-04 19:25:40 -07:00
use ast::ExpressionType::*;
2018-05-28 23:39:58 -07:00
Ok(match expr {
NatLiteral(_) => Type::Const(Nat),
StringLiteral(_) => Type::Const(StringT),
2018-06-03 02:49:54 -07:00
BinExp(op, lhs, rhs) => {
return Err(format!("NOTDONE"))
},
2018-05-29 00:09:12 -07:00
Call { f, arguments } => {
return Err(format!("NOTDONE"))
},
2018-05-29 00:57:27 -07:00
Value(name) => {
2018-06-03 02:20:14 -07:00
let s = match self.0.get(name) {
Some(sigma) => sigma.clone(),
2018-05-29 00:57:27 -07:00
None => return Err(format!("Unknown variable: {}", name))
2018-06-03 02:20:14 -07:00
};
self.instantiate(s)
2018-05-29 00:57:27 -07:00
},
2018-05-28 23:39:58 -07:00
_ => Type::Const(Unit)
})
}
}
2018-05-22 00:36:02 -07:00
/* GIANT TODO - use the rust im crate, unless I make this code way less haskell-ish after it's done
*/
2018-05-22 00:36:02 -07:00
/*
2018-05-20 23:44:12 -07:00
pub type TypeResult<T> = Result<T, String>;
*/
2018-05-15 23:58:06 -07:00
/* TODO this should just check the name against a map, and that map should be pre-populated with
* types */
/*
impl parsing::TypeName {
fn to_type(&self) -> TypeResult<Type> {
2018-05-15 23:58:06 -07:00
use self::parsing::TypeSingletonName;
use self::parsing::TypeName::*;
2018-05-16 01:08:06 -07:00
use self::Type::*; use self::TConstOld::*;
Ok(match self {
2018-05-15 23:58:06 -07:00
Tuple(_) => return Err(format!("Tuples not yet implemented")),
Singleton(name) => match name {
TypeSingletonName { name, .. } => match &name[..] {
2018-05-16 01:08:06 -07:00
/*
2018-05-12 01:44:03 -07:00
"Nat" => Const(Nat),
"Int" => Const(Int),
"Float" => Const(Float),
"Bool" => Const(Bool),
"String" => Const(StringT),
2018-05-16 01:08:06 -07:00
*/
n => Const(Custom(n.to_string()))
}
}
})
}
}
*/
2018-02-26 21:43:53 -08:00
2018-05-15 21:53:50 -07:00
/*
impl TypeContext {
pub fn type_check_ast(&mut self, ast: &parsing::AST) -> TypeResult<String> {
2018-05-15 21:53:50 -07:00
let ref block = ast.0;
2018-05-17 23:21:23 -07:00
let mut infer = Infer::default();
let env = TypeEnvironment::default();
let output = infer.infer_block(block, &env);
2018-05-17 02:29:17 -07:00
match output {
Ok(s) => Ok(format!("{:?}", s)),
Err(s) => Err(format!("Error: {:?}", s))
}
2018-05-15 21:53:50 -07:00
}
2018-02-26 21:43:53 -08:00
}
2018-05-17 00:36:51 -07:00
// this is the equivalent of the Haskell Infer monad
2018-05-17 23:21:23 -07:00
#[derive(Debug, Default)]
2018-05-17 00:36:51 -07:00
struct Infer {
2018-05-17 23:21:23 -07:00
_idents: u32,
2018-05-17 00:36:51 -07:00
}
2018-05-17 02:29:17 -07:00
#[derive(Debug)]
enum InferError {
CannotUnify(MonoType, MonoType),
OccursCheckFailed(Rc<String>, MonoType),
2018-05-18 03:12:18 -07:00
UnknownIdentifier(Rc<String>),
Custom(String),
2018-05-17 02:29:17 -07:00
}
2018-05-18 01:43:51 -07:00
type InferResult<T> = Result<T, InferError>;
2018-05-17 00:36:51 -07:00
impl Infer {
2018-05-17 23:21:23 -07:00
fn fresh(&mut self) -> MonoType {
let i = self._idents;
self._idents += 1;
let name = Rc::new(format!("{}", ('a' as u8 + 1) as char));
MonoType::Var(name)
2018-05-17 00:36:51 -07:00
}
2018-05-18 01:43:51 -07:00
fn unify(&mut self, a: MonoType, b: MonoType) -> InferResult<Substitution> {
2018-05-17 23:13:53 -07:00
use self::InferError::*; use self::MonoType::*;
Ok(match (a, b) {
(Const(ref a), Const(ref b)) if a == b => Substitution::new(),
(Var(ref name), ref var) => Substitution::bind_variable(name, var),
(ref var, Var(ref name)) => Substitution::bind_variable(name, var),
(Function(box a1, box b1), Function(box a2, box b2)) => {
let s1 = self.unify(a1, a2)?;
let s2 = self.unify(b1.apply_substitution(&s1), b2.apply_substitution(&s1))?;
s1.merge(s2)
},
(a, b) => return Err(CannotUnify(a, b))
})
}
2018-05-17 00:36:51 -07:00
2018-05-18 01:43:51 -07:00
fn infer_block(&mut self, block: &Vec<parsing::Statement>, env: &TypeEnvironment) -> InferResult<MonoType> {
use self::parsing::Statement;
let mut ret = MonoType::Const(TypeConst::Unit);
for statement in block.iter() {
ret = match statement {
Statement::ExpressionStatement(expr) => {
let (sub, ty) = self.infer_expr(expr, env)?;
//TODO handle substitution monadically
ty
}
Statement::Declaration(decl) => MonoType::Const(TypeConst::Unit),
}
}
Ok(ret)
}
2018-05-18 01:43:51 -07:00
fn infer_expr(&mut self, expr: &parsing::Expression, env: &TypeEnvironment) -> InferResult<(Substitution, MonoType)> {
use self::parsing::Expression;
match expr {
Expression(e, Some(anno)) => self.infer_annotated_expr(e, anno, env),
/*
let anno_ty = anno.to_type()?;
let ty = self.infer_exprtype(&e)?;
self.unify(ty, anno_ty)
},
*/
Expression(e, None) => self.infer_exprtype(e, env)
}
}
fn infer_annotated_expr(&mut self, expr: &parsing::ExpressionType, anno: &parsing::TypeName, env: &TypeEnvironment) -> InferResult<(Substitution, MonoType)> {
2018-05-18 03:12:18 -07:00
Err(InferError::Custom(format!("exprtype not done: {:?}", expr)))
}
fn infer_exprtype(&mut self, expr: &parsing::ExpressionType, env: &TypeEnvironment) -> InferResult<(Substitution, MonoType)> {
use self::parsing::ExpressionType::*;
use self::TypeConst::*;
Ok(match expr {
NatLiteral(_) => (Substitution::new(), MonoType::Const(Nat)),
FloatLiteral(_) => (Substitution::new(), MonoType::Const(Float)),
StringLiteral(_) => (Substitution::new(), MonoType::Const(StringT)),
BoolLiteral(_) => (Substitution::new(), MonoType::Const(Bool)),
2018-05-19 01:57:03 -07:00
Value(name) => match env.lookup(name) {
Some(sigma) => {
let tau = self.instantiate(&sigma);
(Substitution::new(), tau)
},
None => return Err(InferError::UnknownIdentifier(name.clone())),
},
2018-05-18 03:12:18 -07:00
e => return Err(InferError::Custom(format!("Type inference for {:?} not done", e)))
})
}
2018-05-19 01:57:03 -07:00
fn instantiate(&mut self, sigma: &PolyType) -> MonoType {
let ref ty: MonoType = sigma.1;
let mut subst = Substitution::new();
for name in sigma.0.iter() {
let fresh_mvar = self.fresh();
let new = Substitution::bind_variable(name, &fresh_mvar);
subst = subst.merge(new);
}
ty.apply_substitution(&subst)
}
}
*/
/* OLD STUFF DOWN HERE */
2018-05-17 00:36:51 -07:00
/*
2018-02-26 21:43:53 -08:00
impl TypeContext {
2018-05-15 22:08:37 -07:00
fn infer_block(&mut self, statements: &Vec<parsing::Statement>) -> TypeResult<Type> {
2018-05-15 21:53:50 -07:00
let mut ret_type = Type::Const(TConst::Unit);
for statement in statements {
2018-05-15 22:08:37 -07:00
ret_type = self.infer_statement(statement)?;
2018-02-21 02:31:28 -08:00
}
Ok(ret_type)
}
2018-05-15 21:53:50 -07:00
2018-05-15 22:08:37 -07:00
fn infer_statement(&mut self, statement: &parsing::Statement) -> TypeResult<Type> {
2018-02-21 02:31:28 -08:00
use self::parsing::Statement::*;
match statement {
2018-05-15 14:26:11 -07:00
ExpressionStatement(expr) => self.infer(expr),
Declaration(decl) => self.add_declaration(decl),
2018-02-21 02:31:28 -08:00
}
}
2018-02-22 03:21:58 -08:00
fn add_declaration(&mut self, decl: &parsing::Declaration) -> TypeResult<Type> {
use self::parsing::Declaration::*;
2018-02-21 02:31:28 -08:00
use self::Type::*;
2018-02-22 03:21:58 -08:00
match decl {
Binding { name, expr, .. } => {
2018-02-22 19:59:53 -08:00
let ty = self.infer(expr)?;
2018-02-22 03:21:58 -08:00
self.bindings.insert(name.clone(), ty);
},
_ => return Err(format!("other formats not done"))
}
Ok(Void)
2018-02-21 02:31:28 -08:00
}
2018-02-22 19:59:53 -08:00
fn infer(&mut self, expr: &parsing::Expression) -> TypeResult<Type> {
2018-02-21 03:39:40 -08:00
use self::parsing::Expression;
match expr {
2018-05-15 14:26:11 -07:00
Expression(e, Some(anno)) => {
let anno_ty = anno.to_type()?;
2018-02-22 03:21:58 -08:00
let ty = self.infer_exprtype(&e)?;
self.unify(ty, anno_ty)
},
2018-05-15 14:26:11 -07:00
Expression(e, None) => self.infer_exprtype(e)
2018-02-21 14:14:24 -08:00
}
}
2018-02-22 03:21:58 -08:00
fn infer_exprtype(&mut self, expr: &parsing::ExpressionType) -> TypeResult<Type> {
2018-02-21 14:14:24 -08:00
use self::parsing::ExpressionType::*;
use self::Type::*; use self::TConst::*;
match expr {
2018-05-15 14:26:11 -07:00
NatLiteral(_) => Ok(Const(Nat)),
FloatLiteral(_) => Ok(Const(Float)),
StringLiteral(_) => Ok(Const(StringT)),
BoolLiteral(_) => Ok(Const(Bool)),
BinExp(op, lhs, rhs) => { /* remember there are both the haskell convention talk and the write you a haskell ways to do this! */
match op.get_type()? {
2018-02-23 01:49:37 -08:00
Func(box t1, box Func(box t2, box t3)) => {
let lhs_ty = self.infer(lhs)?;
let rhs_ty = self.infer(rhs)?;
self.unify(t1, lhs_ty)?;
self.unify(t2, rhs_ty)?;
Ok(t3)
},
2018-02-26 18:23:10 -08:00
other => Err(format!("{:?} is not a binary function type", other))
2018-02-23 01:49:37 -08:00
}
2018-02-22 19:59:53 -08:00
},
2018-05-15 14:26:11 -07:00
PrefixExp(op, expr) => match op.get_type()? {
2018-02-26 02:21:21 -08:00
Func(box t1, box t2) => {
let expr_ty = self.infer(expr)?;
self.unify(t1, expr_ty)?;
Ok(t2)
},
2018-02-26 18:23:10 -08:00
other => Err(format!("{:?} is not a prefix op function type", other))
},
2018-05-15 14:26:11 -07:00
Value(name) => {
2018-02-26 18:23:10 -08:00
match self.bindings.get(name) {
Some(ty) => Ok(ty.clone()),
None => Err(format!("No binding found for variable: {}", name)),
}
2018-02-26 02:21:21 -08:00
},
2018-05-15 14:26:11 -07:00
Call { f, arguments } => {
2018-02-26 21:28:11 -08:00
let mut tf = self.infer(f)?;
for arg in arguments.iter() {
match tf {
Func(box t, box rest) => {
let t_arg = self.infer(arg)?;
self.unify(t, t_arg)?;
tf = rest;
},
other => return Err(format!("Function call failed to unify; last type: {:?}", other)),
}
}
Ok(tf)
},
2018-05-15 14:26:11 -07:00
TupleLiteral(expressions) => {
2018-03-03 11:55:20 -08:00
let mut types = vec![];
for expr in expressions {
types.push(self.infer(expr)?);
}
Ok(Sum(types))
},
2018-02-21 14:14:24 -08:00
_ => Err(format!("Type not yet implemented"))
2018-02-21 03:39:40 -08:00
}
}
fn unify(&mut self, t1: Type, t2: Type) -> TypeResult<Type> {
use self::Type::*;// use self::TConst::*;
match (t1, t2) {
(Const(ref a), Const(ref b)) if a == b => Ok(Const(a.clone())),
(a, b) => Err(format!("Types {:?} and {:?} don't unify", a, b))
}
}
2018-02-21 02:31:28 -08:00
}
*/
2018-02-21 02:31:28 -08:00
2018-05-29 00:21:03 -07:00
#[cfg(test)]
mod tests {
2018-06-04 19:25:40 -07:00
/*
2018-05-29 00:21:03 -07:00
use super::{Type, TConst, TypeContext};
use super::Type::*;
use super::TConst::*;
2018-06-04 20:36:26 -07:00
use std::rc::Rc;
use std::cell::RefCell;
2018-05-29 00:21:03 -07:00
macro_rules! type_test {
($input:expr, $correct:expr) => {
{
2018-06-04 20:36:26 -07:00
let symbol_table = Rc::new(RefCell::new(SymbolTable::new()));
let mut tc = TypeContext::new(symbol_table);
2018-06-04 19:25:40 -07:00
let ast = ::ast::parse(::tokenizing::tokenize($input)).0.unwrap() ;
2018-05-29 00:21:03 -07:00
//tc.add_symbols(&ast);
assert_eq!($correct, tc.infer_block(&ast.0).unwrap())
}
}
}
#[test]
fn basic_inference() {
type_test!("30", Const(Nat));
//type_test!("fn x(a: Int): Bool {}; x(1)", TConst(Boolean));
}
2018-06-04 19:25:40 -07:00
*/
2018-05-29 00:21:03 -07:00
}