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
use std::fmt;
use std::sync::mpsc;
use crate::Locker;
use std::thread;
use crate::{
    exp, exp_assert, CallSnapshot, Environment, Exception, ExceptionValue as EV, SourcePosition,
    Value,
};
#[derive(Debug, Clone)]
pub struct Expression {
    value: Value,
    source: Option<SourcePosition>,
}
impl PartialEq for Expression {
    fn eq(&self, other: &Self) -> bool {
        
        self.value == other.value
    }
}
impl Expression {
    pub fn new(value: Value) -> Self {
        Self {
            value,
            source: None,
        }
    }
    pub fn with_source(mut self, source_position: SourcePosition) -> Self {
        self.source = Some(source_position);
        self
    }
    pub fn nil() -> Self {
        Self {
            value: Value::List(vec![]),
            source: None,
        }
    }
    pub fn t() -> Self {
        Self {
            value: Value::True,
            source: None,
        }
    }
    pub fn get_value(&self) -> &Value {
        &self.value
    }
    pub fn into_value(self) -> Value {
        self.value
    }
    pub fn source(&self) -> &'_ Option<SourcePosition> {
        &self.source
    }
    pub fn eval_async(
        self,
        parent_snapshot: Locker<CallSnapshot>,
        env: Locker<Environment>,
    ) -> Result<mpsc::Receiver<Result<Self, Exception>>, Exception> {
        let exp = self;
        let snap = parent_snapshot.clone();
        
        let (sender, receiver) = mpsc::channel::<Result<Self, Exception>>();
        if let Ok(th) = thread::Builder::new()
            .stack_size(64 * 1024 * 1024)
            .spawn(move || {
                sender.send(exp.eval(snap, env)).unwrap();
            })
        {
            match th.join() {
                Ok(_) => {}
                Err(_) => {
                    return Err(Exception::new(
                        EV::Concurrency,
                        Some(parent_snapshot),
                        Some("could not wait for thread to finish executing".to_string()),
                    ))
                }
            }
        };
        Ok(receiver)
    }
    pub fn eval(
        &self,
        parent_snapshot: Locker<CallSnapshot>,
        env: Locker<Environment>,
    ) -> Result<Self, Exception> {
        use Value::*;
        let snapshot = CallSnapshot::new(&self, &parent_snapshot)?;
        let snap = || snapshot.clone();
        match &self.value {
            List(vals) => {
                if !vals.is_empty() {
                    let operator = vals.get(0).unwrap();
                    let arguments: Vec<&Expression> = vals.iter().skip(1).collect();
                    match &operator.value {
                        Operator(operand) => operand.apply(snapshot, arguments, self, env),
                        List(_) | Symbol(_) => {
                            let evaled_operator = operator.eval(snap(), env.clone())?;
                            let mut new_list = vec![evaled_operator];
                            for arg in arguments {
                                new_list.push(arg.clone());
                            }
                            Expression::new(Value::List(new_list)).eval(snap(), env)
                        }
                        Lambda(function) | Macro(function) => {
                            let mut scoped_env = match &operator.value {
                                Lambda(_) => Environment::root()
                                    .with_parent(function.lexical_scope.clone(), None),
                                Macro(_) => {
                                    let mut env =
                                        Environment::root().with_parent(env.clone(), None);
                                    env.add_parent(function.lexical_scope.clone(), None);
                                    env
                                }
                                _ => unreachable!(),
                            };
                            if function.collapse_input {
                                let sym = function.params.get(0).unwrap(); 
                                let args_evaled = {
                                    let mut list = Vec::new();
                                    for arg_expr in arguments {
                                        list.push(match &operator.value {
                                            Lambda { .. } => arg_expr.eval(snap(), env.clone())?,
                                            Macro { .. } => arg_expr.clone(),
                                            _ => unreachable!(),
                                        });
                                    }
                                    list
                                };
                                let arg = Expression::new(Value::List(args_evaled));
                                scoped_env.assign(sym.clone(), arg, true, snap())?;
                            } else {
                                exp_assert!(
                                    function.params.len() == arguments.len(),
                                    EV::ArgumentMismatch(
                                        arguments.len(),
                                        format!("{}", function.params.len())
                                    ),
                                    snap()
                                );
                                for (symbol, arg_expr) in
                                    function.params.iter().zip(arguments.into_iter())
                                {
                                    let arg_evaled = match &operator.value {
                                        Lambda { .. } => arg_expr.eval(snap(), env.clone())?,
                                        Macro { .. } => arg_expr.clone(),
                                        _ => unreachable!(),
                                    };
                                    scoped_env.assign(symbol.clone(), arg_evaled, true, snap())?;
                                }
                            }
                            if let Macro { .. } = &operator.value {
                                scoped_env = scoped_env.shadow();
                            };
                            let mut result = Expression::nil();
                            let scoped_env_lock = Locker::new(scoped_env);
                            for exp in &function.expressions {
                                result = exp.eval(snap(), scoped_env_lock.clone())?;
                            }
                            Ok(result)
                        }
                        val => exp!(EV::InvalidOperator(val.clone()), snapshot),
                    }
                } else {
                    Ok(self.clone())
                }
            }
            Symbol(sym) => match env
                .read()
                .expect("unable to access environment (are threads locked?)")
                .lookup(&sym)
            {
                Some(exp) => Ok(exp.read().unwrap().clone()), 
                None => exp!(EV::UndefinedSymbol(sym.clone()), snapshot),
            },
            _ => Ok(self.clone()),
        }
    }
}
impl fmt::Display for Expression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.value)
    }
}
impl PartialOrd for Expression {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.value.partial_cmp(&other.value)
    }
}