aboutsummaryrefslogtreecommitdiff
path: root/src/type/util.rs
blob: ad85b79663ab7feb6ddbf5856369bb603981eaf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

use crate::r#type::{*, Type::*, TypeError::*, FunDefError::*};
use std::collections::HashMap;

pub fn arr(a: impl Into<Box<Type>>, b: impl Into<Box<Type>>) -> Type {
    Arrow(a.into(), b.into())
}

pub fn vt(name: &str) -> Type {
    VarType(name.to_string())
}

pub fn vecof(ty: impl Into<Box<Type>>) -> Type {
    VecOf(ty.into())
}

use crate::sexp::{SExp::*, SLeaf::*};
impl SExp {
    pub fn get_fun_type(self, mut ctx: HashMap<String, Type>) -> Result<Type, TypeError> {
	let ls = self.clone().parts();
	ls.get(0)
	    .filter(|t| **t == Atom(Fun))
	    .ok_or(InvalidFunDef(self.clone(), NoFunToken))?;
	let argnames = ls.get(1)
	    .ok_or(InvalidFunDef(self.clone(), NoArgumentList))?
	    .clone().parts();
	let argtype = ls.get(2)
	    .ok_or(InvalidFunDef(self.clone(), NoTypeList))?
	    .clone();
	let rettype  = ls.get(3)
	    .ok_or(InvalidFunDef(self.clone(), NoReturnType))?;
	let funbody  = ls.get(4)
	    .ok_or(InvalidFunDef(self.clone(), NoFunctionBody))?;

	let mut argnamevec = vec![];
	for name in argnames {
	    argnamevec.push(match name {
		Atom(Var(s)) => Ok(s),
		_ => Err(InvalidFunDef(self.clone(), InvalidArgumentList)),
	    }?);
	}

	let argtypes = match argtype {
	    Atom(Ty(List(v))) => Ok(v),
	    Atom(Ty(t)) => Ok(vec![t]),
	    _ => {
		Err(InvalidFunDef(self.clone(), InvalidArgumentList))
	    },
	}?;

	let rettype = match rettype.clone().multistep() {
	    Ok(Atom(Ty(t))) => Ok(t),
	    _ => Err(InvalidFunDef(self.clone(), InvalidReturnType))
	}?;

	let additional_ctx = argnamevec.into_iter().zip(argtypes.clone());
	for (name, ty) in additional_ctx {
	    ctx.insert(name, ty);
	}

	let argtype = if argtypes.len() == 0 {
	    NilType
	} else if argtypes.len() == 1 {
	    argtypes[0].clone()
	} else {
	    List(argtypes)
	};

	funbody.infer_type(ctx)?;

	Ok(arr(argtype, rettype))
    }
}