summaryrefslogtreecommitdiff
path: root/src/semantic/translate.rs
blob: 7e0d2b8fbe7139e5c89813bd717c47ee7c04d9c9 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Copyright ⓒ 2017 David Li.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use ::ast::{self, WithLocation};
use super::environment;
use super::types::{self, Ty};

#[derive(Debug)]
pub enum TypeError {
    Unimplemented,
    Mismatch {
        expected: Ty,
        actual: Ty,
    },
    UnboundName,
}

type TypeEnvironment<'a> = environment::Environment<'a, String, Ty>;
pub type Result = ::std::result::Result<Ty, WithLocation<TypeError>>;

pub fn translate(program: &ast::Program) -> Result {
    let mut venv = TypeEnvironment::new(None);
    let mut tenv = TypeEnvironment::new(None);
    tenv.add_binding("int".into(), Ty::Int);
    tenv.add_binding("string".into(), Ty::String);
    trans_exp(&mut venv, &mut tenv, &*program.0)
}

macro_rules! err {
    ($exp: expr, $err: expr) => {
        Err(WithLocation::new($err, $exp.start, $exp.end))
    }
}

fn trans_ty<'a>(
    venv: &mut TypeEnvironment<'a>,
    tenv: &mut TypeEnvironment<'a>,
    ty: &WithLocation<ast::Ty>) -> Result {
    match ty.value {
        ast::Ty::Name(ref name) => {
            tenv.lookup(&name)
                .map(|v| v.clone())
                .ok_or(WithLocation::new(TypeError::UnboundName, ty.start, ty.end))
        }
        ast::Ty::Array(ref inner_ty) => {
            trans_ty(venv, tenv, &inner_ty)
        },
        ast::Ty::Record(ref fields) => {
            let mut result = vec![];
            for field in fields {
                result.push(types::RecordField::new(
                    field.name.clone(),
                    trans_ty(venv, tenv, &field.ty)?));
            }
            Ok(Ty::Record(result))
        },
    }
}

fn trans_decl<'a>(
    venv: &mut TypeEnvironment<'a>,
    tenv: &mut TypeEnvironment<'a>,
    decl: &WithLocation<ast::Declaration>) -> Result {
    match decl.declaration {
        ast::DeclarationBody::Fun { .. } => {
            err!(decl, TypeError::Unimplemented)
        }
        ast::DeclarationBody::Ty { ref ty } => {
            trans_ty(venv, tenv, ty)
        }
        ast::DeclarationBody::Var { ref ty, ref value } => {
            let actual_ty = trans_exp(venv, tenv, &value)?;
            if let &Some(ref ty) = ty {
                let decl_ty = trans_ty(venv, tenv, &ty)?;
                if decl_ty != actual_ty {
                    return err!(ty, TypeError::Mismatch {
                        expected: decl_ty,
                        actual: actual_ty,
                    });
                }
            }
            Ok(actual_ty)
        }
    }
}

fn trans_exp<'a>(
    venv: &mut TypeEnvironment<'a>,
    tenv: &mut TypeEnvironment<'a>,
    exp: &WithLocation<ast::Expression>) -> Result {
    use ast::Expression::*;

    match &exp.value {
        &Let(ref decls, ref body) => {
            let mut new_venv = TypeEnvironment::new(Some(venv));
            let mut new_tenv = TypeEnvironment::new(Some(tenv));
            for decl in decls.iter() {
                let decl_ty = trans_decl(&mut new_venv, &mut new_tenv, decl)?;
                match decl.declaration {
                    ast::DeclarationBody::Fun { .. } | ast::DeclarationBody::Var { .. } => {
                        new_venv.add_binding(decl.name.clone(), decl_ty);
                    }
                    ast::DeclarationBody::Ty { .. } => {
                        new_tenv.add_binding(decl.name.clone(), decl_ty);
                    }
                }
            }
            trans_exp(&mut new_venv, &mut new_tenv, &*body)
        },
        &UnaryOp(ref op, ref operand) => {
            use ast::UnaryOp::*;
            let operand_ty = trans_exp(venv, tenv, operand)?;
            match op {
                &Neg | &Pos => {
                    match operand_ty {
                        Ty::Int => {
                            Ok(Ty::Int)
                        }
                        other => {
                            err!(operand, TypeError::Mismatch {
                                expected: Ty::Int,
                                actual: other,
                            })
                        }
                    }
                }
                &Not => {
                    err!(exp, TypeError::Unimplemented)
                }
            }
        },
        &BinOp(ref op, ref left, ref right) => {
            use ast::BinOp::*;
            let left_ty = trans_exp(venv, tenv, left)?;
            let right_ty = trans_exp(venv, tenv, right)?;
            match op {
                &Add => {
                    match (left_ty, right_ty) {
                        (Ty::Int, Ty::Int) => {
                            Ok(Ty::Int)
                        }
                        (Ty::String, Ty::String) => {
                            Ok(Ty::String)
                        }
                        (Ty::Int, other) => {
                            err!(right, TypeError::Mismatch {
                                expected: Ty::Int,
                                actual: other,
                            })
                        }
                        (Ty::String, other) => {
                            err!(right, TypeError::Mismatch {
                                expected: Ty::String,
                                actual: other,
                            })
                        }
                        _ => {
                            err!(exp, TypeError::Unimplemented)
                        }
                    }
                }
                _ => {
                    err!(exp, TypeError::Unimplemented)
                }
            }
        },
        &Number(_) => Ok(Ty::Int),
        &String(_) => Ok(Ty::String),
        &Name(ref name) => {
            if let Some(ty) = venv.lookup(name) {
                Ok(ty.clone())
            }
            else {
                err!(exp, TypeError::UnboundName)
            }
        },
        &Nil => {
            Err(WithLocation::new(TypeError::Unimplemented, exp.start, exp.end))
        },
    }
}