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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
|
use std::{convert::TryFrom, fmt};
use crate::app::AppState;
use crate::lisp::{
error::{EvalError, LispError},
eval::lookup_extended,
number::LispNumber,
EnvList,
};
#[derive(Debug, Copy, PartialEq, Clone)]
pub enum Arity {
Exact(usize),
Atleast(usize),
Atmost(usize),
Range(usize, usize),
None,
}
impl Arity {
pub fn is_valid<T>(self, args: &[T]) -> bool {
match self {
Arity::Exact(a) => args.len() == a,
Arity::Atleast(a) => args.len() >= a,
Arity::Atmost(a) => args.len() <= a,
Arity::Range(low, high) => args.len() >= low && args.len() <= high,
Arity::None => true,
}
}
pub fn to_error(self) -> LispError {
LispError::Eval(EvalError::ArgumentCount(self))
}
}
#[derive(Clone)]
pub struct PrimitiveFunc {
pub arity: Arity, // minimim arity
pub closure: fn(&[LispExpr], &mut AppState) -> Result<LispExpr, LispError>,
}
impl PrimitiveFunc {
pub fn call(&self, args: &[LispExpr], app: &mut AppState) -> Result<LispExpr, LispError> {
if !self.arity.is_valid(args) {
return Err(EvalError::ArgumentCount(self.arity).into());
}
(self.closure)(args, app)
}
}
pub type Ident = String;
pub type BoolLit = bool;
#[derive(Clone)]
pub struct LispFunction {
pub params: Vec<String>,
pub body: Vec<LispExpr>,
}
#[derive(Clone)]
pub enum LispExpr {
Unit,
Number(LispNumber),
List(Vec<LispExpr>),
StringLit(String),
BoolLit(bool),
Ident(Ident),
PrimitiveFunc(PrimitiveFunc),
Function(LispFunction),
Char(char),
// none of these depths should be zero
Quasiquote(Box<LispExpr>, u32),
Comma(Box<LispExpr>, u32),
CommaAt(Box<LispExpr>, u32),
Quote(Box<LispExpr>, u32),
}
impl LispExpr {
pub fn comma(self, n: u32) -> LispExpr {
match self {
LispExpr::Comma(v, i) => LispExpr::Comma(v, i.checked_add(n).expect("comma overflow")),
LispExpr::CommaAt(v, i) => LispExpr::CommaAt(v, i + n),
v => LispExpr::Comma(Box::new(v), n),
}
}
pub fn comma_at(self, n: u32) -> LispExpr {
match self {
LispExpr::CommaAt(v, i) => {
LispExpr::CommaAt(v, i.checked_add(n).expect("comma_at overflow"))
}
v => LispExpr::CommaAt(Box::new(v), n),
}
}
pub fn quote(self, n: u32) -> LispExpr {
match self {
LispExpr::Quote(v, i) => LispExpr::Quote(v, i.checked_add(n).expect("quote overflow")),
v => LispExpr::Quote(Box::new(v), n),
}
}
pub fn quasiquote(self, n: u32) -> LispExpr {
match self {
LispExpr::Quasiquote(v, i) => {
LispExpr::Quasiquote(v, i.checked_add(n).expect("quasiquote overflow"))
}
v => LispExpr::Quasiquote(Box::new(v), n),
}
}
pub fn compare(&self, other: &Self, envs: &EnvList) -> Result<BoolLit, LispError> {
match (self, other) {
(LispExpr::Unit, LispExpr::Unit) => Ok(true),
(LispExpr::Number(s), LispExpr::Number(o)) => Ok(s == o),
(LispExpr::List(s), LispExpr::List(o)) => Ok(s
.iter()
.zip(o)
.all(|(a, b)| matches!(a.compare(b, envs), Ok(true)))),
(LispExpr::StringLit(s), LispExpr::StringLit(o)) => Ok(s == o),
(LispExpr::Char(s), LispExpr::Char(o)) => Ok(s == o),
(LispExpr::BoolLit(s), LispExpr::BoolLit(o)) => Ok(s == o),
(LispExpr::Ident(s), LispExpr::Ident(o)) => {
let s = lookup_extended(envs, s)?;
let o = lookup_extended(envs, o)?;
s.compare(&o, envs)
}
(LispExpr::PrimitiveFunc(s), LispExpr::PrimitiveFunc(o)) => {
let PrimitiveFunc { closure: s, .. } = s;
let PrimitiveFunc { closure: o, .. } = o;
Ok(*s as usize == *o as usize)
}
(LispExpr::Function(_), LispExpr::Function(_)) => Err(EvalError::BadForm.into()),
(LispExpr::Quasiquote(s, sd), LispExpr::Quasiquote(o, od)) => {
Ok(s.compare(o, envs)? && sd == od)
}
(LispExpr::Comma(s, sd), LispExpr::Comma(o, od)) => Ok(s.compare(o, envs)? && sd == od),
(LispExpr::CommaAt(s, sd), LispExpr::CommaAt(o, od)) => {
Ok(s.compare(o, envs)? && sd == od)
}
(LispExpr::Quote(s, sd), LispExpr::Quote(o, od)) => Ok(s.compare(o, envs)? && sd == od),
_ => Err(EvalError::TypeMismatch.into()),
}
}
}
impl fmt::Display for LispExpr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LispExpr::Unit => write!(f, "()")?,
LispExpr::Number(n) => write!(f, "{}", n)?,
LispExpr::List(l) => {
for expr in l.iter() {
write!(f, " {} ", expr)?
}
}
LispExpr::StringLit(s) => write!(f, "{}", s)?,
LispExpr::Char(c) => write!(f, "{}", c)?,
LispExpr::BoolLit(b) => {
if *b {
write!(f, "#t")?
} else {
write!(f, "#f")?
}
}
LispExpr::Ident(s) => write!(f, "{}", s)?,
LispExpr::PrimitiveFunc(_) => write!(f, "<#primitive>")?,
LispExpr::Function(func) => write!(f, "<#lambda {}>", func.params.join(" "))?,
LispExpr::Quasiquote(val, depth) => {
write!(f, "{}{}", "`".repeat(*depth as usize), val)?
}
LispExpr::Comma(val, depth) => write!(f, "{}{}", ",".repeat(*depth as usize), val)?,
LispExpr::CommaAt(val, depth) => write!(f, "{}@{}", ",".repeat(*depth as usize), val)?,
LispExpr::Quote(val, depth) => write!(f, "{}{}", "'".repeat(*depth as usize), val)?,
};
Ok(())
}
}
impl TryFrom<LispExpr> for LispNumber {
type Error = LispError;
fn try_from(value: LispExpr) -> Result<Self, Self::Error> {
match value {
LispExpr::Number(i) => Ok(i),
_ => Err(LispError::Eval(EvalError::TypeMismatch)),
}
}
}
impl<'a> TryFrom<&'a LispExpr> for &'a LispNumber {
type Error = LispError;
fn try_from(value: &'a LispExpr) -> Result<Self, Self::Error> {
match value {
LispExpr::Number(i) => Ok(i),
_ => Err(LispError::Eval(EvalError::TypeMismatch)),
}
}
}
//impl TryFrom<LispExpr> for Ident {
// type Error = LispError;
// fn try_from(value: LispExpr) -> Result<Self, Self::Error> {
// match value {
// LispExpr::Ident(i) => Ok(i),
// _ => Err(LispError::Eval(EvalError::TypeMismatch)),
// }
// }
//}
//
//
impl TryFrom<LispExpr> for String {
type Error = LispError;
fn try_from(value: LispExpr) -> Result<Self, Self::Error> {
match value {
LispExpr::StringLit(i) => Ok(i),
_ => Err(LispError::Eval(EvalError::TypeMismatch)),
}
}
}
impl AsRef<str> for LispExpr {
fn as_ref(&self) -> &str {
match self {
LispExpr::StringLit(i) => &i,
LispExpr::Ident(i) => &i,
_ => panic!("invalid downcast!"),
}
}
}
impl TryFrom<LispExpr> for BoolLit {
type Error = LispError;
fn try_from(value: LispExpr) -> Result<Self, Self::Error> {
match value {
LispExpr::BoolLit(i) => Ok(i),
_ => Err(LispError::Eval(EvalError::TypeMismatch)),
}
}
}
pub fn is_ident<E: AsRef<LispExpr>>(expr: E) -> bool {
matches!(expr.as_ref(), LispExpr::Ident(_))
}
pub fn is_number<E: AsRef<LispExpr>>(expr: E) -> bool {
matches!(expr.as_ref(), LispExpr::Number(_))
}
|