about summary refs log tree commit diff
path: root/src/interpreter/value.rs
blob: 496e9c4230deb92f194adab01fc86ccc6c3fe108 (plain) (blame)
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
use std::convert::TryFrom;
use std::fmt::{self, Display};
use std::ops::{Add, Div, Mul, Neg, Sub};
use std::rc::Rc;

use derive_more::{Deref, From, TryInto};

use super::{Error, Result};
use crate::ast::{Expr, FunctionType, Ident, Type};

#[derive(Debug, Clone)]
pub struct Function<'a> {
    pub type_: FunctionType,
    pub args: Vec<Ident<'a>>,
    pub body: Expr<'a>,
}

#[derive(From, TryInto)]
#[try_into(owned, ref)]
pub enum Val<'a> {
    Int(i64),
    Float(f64),
    Bool(bool),
    Function(Function<'a>),
}

impl<'a> fmt::Debug for Val<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Val::Int(x) => f.debug_tuple("Int").field(x).finish(),
            Val::Float(x) => f.debug_tuple("Float").field(x).finish(),
            Val::Bool(x) => f.debug_tuple("Bool").field(x).finish(),
            Val::Function(Function { type_, .. }) => {
                f.debug_struct("Function").field("type_", type_).finish()
            }
        }
    }
}

impl<'a> PartialEq for Val<'a> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Val::Int(x), Val::Int(y)) => x == y,
            (Val::Float(x), Val::Float(y)) => x == y,
            (Val::Bool(x), Val::Bool(y)) => x == y,
            (Val::Function(_), Val::Function(_)) => false,
            (_, _) => false,
        }
    }
}

impl<'a> From<u64> for Val<'a> {
    fn from(i: u64) -> Self {
        Self::from(i as i64)
    }
}

impl<'a> Display for Val<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Val::Int(x) => x.fmt(f),
            Val::Float(x) => x.fmt(f),
            Val::Bool(x) => x.fmt(f),
            Val::Function(Function { type_, .. }) => write!(f, "<{}>", type_),
        }
    }
}

impl<'a> Val<'a> {
    pub fn type_(&self) -> Type {
        match self {
            Val::Int(_) => Type::Int,
            Val::Float(_) => Type::Float,
            Val::Bool(_) => Type::Bool,
            Val::Function(Function { type_, .. }) => Type::Function(type_.clone()),
        }
    }

    pub fn as_type<'b, T>(&'b self) -> Result<&'b T>
    where
        T: TypeOf + 'b + Clone,
        &'b T: TryFrom<&'b Self>,
    {
        <&T>::try_from(self).map_err(|_| Error::InvalidType {
            actual: self.type_(),
            expected: <T as TypeOf>::type_of(),
        })
    }

    pub fn as_function<'b>(&'b self, function_type: FunctionType) -> Result<&'b Function<'a>> {
        match self {
            Val::Function(f) if f.type_ == function_type => Ok(&f),
            _ => Err(Error::InvalidType {
                actual: self.type_(),
                expected: Type::Function(function_type),
            }),
        }
    }
}

#[derive(Debug, PartialEq, Clone, Deref)]
pub struct Value<'a>(Rc<Val<'a>>);

impl<'a> Display for Value<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<'a, T> From<T> for Value<'a>
where
    Val<'a>: From<T>,
{
    fn from(x: T) -> Self {
        Self(Rc::new(x.into()))
    }
}

impl<'a> Neg for Value<'a> {
    type Output = Result<Value<'a>>;

    fn neg(self) -> Self::Output {
        Ok((-self.as_type::<i64>()?).into())
    }
}

impl<'a> Add for Value<'a> {
    type Output = Result<Value<'a>>;

    fn add(self, rhs: Self) -> Self::Output {
        Ok((self.as_type::<i64>()? + rhs.as_type::<i64>()?).into())
    }
}

impl<'a> Sub for Value<'a> {
    type Output = Result<Value<'a>>;

    fn sub(self, rhs: Self) -> Self::Output {
        Ok((self.as_type::<i64>()? - rhs.as_type::<i64>()?).into())
    }
}

impl<'a> Mul for Value<'a> {
    type Output = Result<Value<'a>>;

    fn mul(self, rhs: Self) -> Self::Output {
        Ok((self.as_type::<i64>()? * rhs.as_type::<i64>()?).into())
    }
}

impl<'a> Div for Value<'a> {
    type Output = Result<Value<'a>>;

    fn div(self, rhs: Self) -> Self::Output {
        Ok((self.as_type::<f64>()? / rhs.as_type::<f64>()?).into())
    }
}

pub trait TypeOf {
    fn type_of() -> Type;
}

impl TypeOf for i64 {
    fn type_of() -> Type {
        Type::Int
    }
}

impl TypeOf for bool {
    fn type_of() -> Type {
        Type::Bool
    }
}

impl TypeOf for f64 {
    fn type_of() -> Type {
        Type::Float
    }
}