mech-interpreter 0.3.2

The Mech language runtime.
Documentation
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use crate::*;

// Functions
// ----------------------------------------------------------------------------

pub fn function_define(fxn_def: &FunctionDefine, p: &Interpreter) -> MResult<FunctionDefinition> {
    let fxn_name_id = fxn_def.name.hash();
    let mut new_fxn =
        FunctionDefinition::new(fxn_name_id, fxn_def.name.to_string(), fxn_def.clone());

    for input_arg in &fxn_def.input {
        new_fxn
            .input
            .insert(input_arg.name.hash(), input_arg.kind.clone());
    }

    for output_arg in &fxn_def.output {
        new_fxn
            .output
            .insert(output_arg.name.hash(), output_arg.kind.clone());
    }

    let functions = p.functions();
    let mut functions_brrw = functions.borrow_mut();
    functions_brrw
        .user_functions
        .insert(fxn_name_id, new_fxn.clone());
    functions_brrw
        .dictionary
        .borrow_mut()
        .insert(fxn_name_id, fxn_def.name.to_string());
    p.state
        .borrow()
        .dictionary
        .borrow_mut()
        .insert(fxn_name_id, fxn_def.name.to_string());

    Ok(new_fxn)
}

pub fn function_call(
    fxn_call: &FunctionCall,
    env: Option<&Environment>,
    p: &Interpreter,
) -> MResult<Value> {
    let functions = p.functions();
    let fxn_name_id = fxn_call.name.hash();

    if let Some(user_fxn) = { functions.borrow().user_functions.get(&fxn_name_id).cloned() } {
        let mut input_arg_values = vec![];
        for (_, arg_expr) in fxn_call.args.iter() {
            input_arg_values.push(expression(arg_expr, env, p)?);
        }
        return execute_user_function(&user_fxn, &input_arg_values, p);
    }

    if { functions.borrow().functions.contains_key(&fxn_name_id) } {
        todo!();
    }

    let fxn_compiler = {
        functions
            .borrow()
            .function_compilers
            .get(&fxn_name_id)
            .copied()
    };
    match fxn_compiler {
        Some(fxn_compiler) => {
            let mut input_arg_values = vec![];
            for (_, arg_expr) in fxn_call.args.iter() {
                input_arg_values.push(expression(arg_expr, env, p)?);
            }
            execute_native_function_compiler(fxn_compiler, &input_arg_values, p)
        }
        None => Err(MechError::new(
            MissingFunctionError {
                function_id: fxn_name_id,
            },
            None,
        )
        .with_compiler_loc()
        .with_tokens(fxn_call.name.tokens())),
    }
}

pub fn execute_native_function_compiler(
    fxn_compiler: &'static dyn NativeFunctionCompiler,
    input_arg_values: &Vec<Value>,
    p: &Interpreter,
) -> MResult<Value> {
    let plan = p.plan();
    match fxn_compiler.compile(input_arg_values) {
        Ok(new_fxn) => {
            let mut plan_brrw = plan.borrow_mut();
            new_fxn.solve();
            let result = new_fxn.out();
            plan_brrw.push(new_fxn);
            Ok(result)
        }
        Err(err) => Err(err),
    }
}

fn execute_user_function(
    fxn_def: &FunctionDefinition,
    input_arg_values: &Vec<Value>,
    p: &Interpreter,
) -> MResult<Value> {
    if input_arg_values.len() != fxn_def.input.len() {
        return Err(MechError::new(
            IncorrectNumberOfArguments {
                expected: fxn_def.input.len(),
                found: input_arg_values.len(),
            },
            None,
        )
        .with_compiler_loc()
        .with_tokens(fxn_def.code.name.tokens()));
    }

    let scope = FunctionScope::enter(p);
    bind_function_inputs(fxn_def, input_arg_values, p)?;

    if !fxn_def.code.match_arms.is_empty() {
        let output = execute_function_match_arms(fxn_def, input_arg_values, p);
        drop(scope);
        return output;
    }

    for statement_node in &fxn_def.code.statements {
        statement(statement_node, None, p)?;
    }

    let output = collect_function_output(p, fxn_def);
    drop(scope);
    output
}

fn execute_function_match_arms(
    fxn_def: &FunctionDefinition,
    input_arg_values: &Vec<Value>,
    p: &Interpreter,
) -> MResult<Value> {
    for arm in &fxn_def.code.match_arms {
        let mut env = Environment::new();
        if pattern_matches_arguments(&arm.pattern, input_arg_values, &mut env, p)? {
            let out = expression(&arm.expression, Some(&env), p)?;
            return coerce_function_output_kind(detach_value(&out), fxn_def, p);
        }
    }
    Err(MechError::new(
        FunctionOutputUndefinedError {
            output_id: fxn_def.id,
        },
        None,
    )
    .with_compiler_loc()
    .with_tokens(fxn_def.code.name.tokens()))
}

fn pattern_matches_arguments(
    pattern: &Pattern,
    args: &Vec<Value>,
    env: &mut Environment,
    p: &Interpreter,
) -> MResult<bool> {
    if args.len() == 1 {
        return pattern_matches_value(pattern, &args[0], env, p);
    }
    match pattern {
        Pattern::Tuple(pattern_tuple) => {
            if pattern_tuple.0.len() != args.len() {
                return Ok(false);
            }
            for (pat, arg) in pattern_tuple.0.iter().zip(args.iter()) {
                if !pattern_matches_value(pat, arg, env, p)? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        _ => Ok(false),
    }
}

fn pattern_matches_value(
    pattern: &Pattern,
    value: &Value,
    env: &mut Environment,
    p: &Interpreter,
) -> MResult<bool> {
    match pattern {
        Pattern::Wildcard => Ok(true),
        Pattern::Tuple(pattern_tuple) => match detach_value(value) {
            Value::Tuple(tuple) => {
                let tuple_brrw = tuple.borrow();
                if pattern_tuple.0.len() != tuple_brrw.elements.len() {
                    return Ok(false);
                }
                for (pat, val) in pattern_tuple.0.iter().zip(tuple_brrw.elements.iter()) {
                    if !pattern_matches_value(pat, val, env, p)? {
                        return Ok(false);
                    }
                }
                Ok(true)
            }
            _ => Ok(false),
        },
        Pattern::Expression(Expression::Var(var)) => {
            let var_id = var.name.hash();
            let detached = detach_value(value);
            if let Some(existing) = env.get(&var_id) {
                Ok(existing == &detached)
            } else {
                env.insert(var_id, detached);
                Ok(true)
            }
        }
        Pattern::Expression(expr) => {
            if let Some(var_id) = extract_pattern_variable_id(expr) {
                let detached = detach_value(value);
                if let Some(existing) = env.get(&var_id) {
                    return Ok(existing == &detached);
                }
                env.insert(var_id, detached);
                return Ok(true);
            }
            let expected = expression(expr, Some(env), p)?;
            Ok(values_match(&detach_value(&expected), &detach_value(value)))
        }
        Pattern::TupleStruct(_) => Ok(false),
    }
}

fn extract_pattern_variable_id(expr: &Expression) -> Option<u64> {
    match expr {
        Expression::Var(var) => Some(var.name.hash()),
        Expression::Formula(factor) => match factor {
            Factor::Expression(inner_expr) => extract_pattern_variable_id(inner_expr),
            Factor::Term(term) if term.rhs.is_empty() => extract_pattern_variable_id_from_term(&term.lhs),
            _ => None,
        },
        _ => None,
    }
}

fn extract_pattern_variable_id_from_term(factor: &Factor) -> Option<u64> {
    match factor {
        Factor::Expression(expr) => extract_pattern_variable_id(expr),
        Factor::Parenthetical(inner) => extract_pattern_variable_id_from_term(inner),
        _ => None,
    }
}

fn values_match(expected: &Value, actual: &Value) -> bool {
    if expected == actual {
        return true;
    }
    #[cfg(all(feature = "u64", feature = "f64"))]
    {
        match (expected, actual) {
            (Value::F64(x), Value::U64(y)) => return (*x.borrow() as u64) == *y.borrow(),
            (Value::U64(x), Value::F64(y)) => return *x.borrow() == (*y.borrow() as u64),
            _ => {}
        }
    }
    false
}

fn coerce_function_output_kind(value: Value, fxn_def: &FunctionDefinition, p: &Interpreter) -> MResult<Value> {
    if fxn_def.output.is_empty() {
        return Ok(value);
    }
    let Some((_, output_kind_annotation)) = fxn_def.output.get_index(0) else {
        return Ok(value);
    };
    #[cfg(feature = "kind_annotation")]
    {
    let target_kind = kind_annotation(&output_kind_annotation.kind, p)?
        .to_value_kind(&p.state.borrow().kinds)?;
    Ok(value.convert_to(&target_kind).unwrap_or(value))
    }
    #[cfg(not(feature = "kind_annotation"))]
    {
        let _ = (output_kind_annotation, p);
        Ok(value)
    }
}

struct FunctionScope {
    state: Ref<ProgramState>,
    previous_symbols: SymbolTableRef,
    previous_plan: Plan,
    previous_environment: Option<SymbolTableRef>,
}

impl FunctionScope {
    fn enter(p: &Interpreter) -> Self {
        let state = p.state.clone();
        let mut state_brrw = state.borrow_mut();
        let mut local_symbols = SymbolTable::new();
        local_symbols.dictionary = state_brrw.dictionary.clone();
        let local_symbols = Ref::new(local_symbols);
        let previous_symbols = std::mem::replace(&mut state_brrw.symbol_table, local_symbols);
        let previous_plan = std::mem::replace(&mut state_brrw.plan, Plan::new());
        let previous_environment = state_brrw.environment.take();
        drop(state_brrw);

        Self {
            state,
            previous_symbols,
            previous_plan,
            previous_environment,
        }
    }
}

impl Drop for FunctionScope {
    fn drop(&mut self) {
        let mut state_brrw = self.state.borrow_mut();
        state_brrw.symbol_table = self.previous_symbols.clone();
        state_brrw.plan = self.previous_plan.clone();
        state_brrw.environment = self.previous_environment.clone();
    }
}

fn bind_function_inputs(
    fxn_def: &FunctionDefinition,
    input_arg_values: &Vec<Value>,
    p: &Interpreter,
) -> MResult<()> {
    let scoped_state = p.state.borrow();
    for ((arg_id, _), input_value) in fxn_def.input.iter().zip(input_arg_values.iter()) {
        let arg_name = fxn_def
            .code
            .input
            .iter()
            .find(|arg| arg.name.hash() == *arg_id)
            .map(|arg| arg.name.to_string())
            .unwrap_or_else(|| arg_id.to_string());
        scoped_state.save_symbol(*arg_id, arg_name, detach_value(input_value), false);
    }
    Ok(())
}

fn collect_function_output(p: &Interpreter, fxn_def: &FunctionDefinition) -> MResult<Value> {
    let symbols = p.symbols();
    let symbols_brrw = symbols.borrow();
    let mut outputs = vec![];

    for output_arg in &fxn_def.code.output {
        let output_id = output_arg.name.hash();
        match symbols_brrw.get(output_id) {
            Some(cell) => outputs.push(detach_value(&cell.borrow())),
            None => {
                return Err(
                    MechError::new(FunctionOutputUndefinedError { output_id }, None)
                        .with_compiler_loc()
                        .with_tokens(output_arg.tokens()),
                );
            }
        }
    }

    Ok(match outputs.len() {
        0 => Value::Empty,
        1 => outputs.remove(0),
        _ => Value::Tuple(Ref::new(MechTuple::from_vec(outputs))),
    })
}

fn detach_value(value: &Value) -> Value {
    match value {
        Value::MutableReference(reference) => detach_value(&reference.borrow()),
        _ => value.clone(),
    }
}

#[derive(Debug, Clone)]
pub struct MissingFunctionError {
    pub function_id: u64,
}

impl MechErrorKind for MissingFunctionError {
    fn name(&self) -> &str {
        "MissingFunction"
    }
    fn message(&self) -> String {
        format!("Function with id {} not found", self.function_id)
    }
}

#[derive(Debug, Clone)]
pub struct FunctionOutputUndefinedError {
    pub output_id: u64,
}

impl MechErrorKind for FunctionOutputUndefinedError {
    fn name(&self) -> &str {
        "FunctionOutputUndefined"
    }
    fn message(&self) -> String {
        format!(
            "Function output {} was declared but never defined",
            self.output_id
        )
    }
}