geam 0.1.1

Experimental Rust-embedded execution runtime for typed Gleam programs
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
mod function_value;
mod primitive;

use crate::plan::{Expr, ExprKind, ListExpr, ReturnExpr, ValueShape};
use crate::planner::error::{InvalidFunctionShapeReason, InvalidTypedAstReason, PlanError};
use ecow::EcoString;

pub(super) fn function_return_expr(
    name: &EcoString,
    expected: &ValueShape,
    actual: Expr,
) -> Result<ReturnExpr, PlanError> {
    let compatible =
        actual.shape().can_flow_to(expected) && actual.value_type() == expected.value_type();
    let return_ = match (actual.into_kind(), expected) {
        (ExprKind::Generic(actual), _) if compatible => Ok(ReturnExpr::generic_body(
            actual.parameter(),
            primitive::generic_return(actual),
        )),
        (ExprKind::Int(actual), _) if compatible => {
            Ok(ReturnExpr::int_body(primitive::int_return(actual)))
        }
        (ExprKind::String(actual), _) if compatible => {
            Ok(ReturnExpr::string_body(primitive::string_return(actual)))
        }
        (ExprKind::BitArray(actual), _) if compatible => Ok(ReturnExpr::bit_array_body(
            primitive::bit_array_return(actual),
        )),
        (ExprKind::UtfCodepoint(actual), _) if compatible => Ok(ReturnExpr::utf_codepoint_body(
            primitive::utf_codepoint_return(actual),
        )),
        (ExprKind::Custom(actual), ValueShape::Custom(signature_shape)) if compatible => Ok(
            ReturnExpr::custom_body(primitive::custom_return(signature_shape.clone(), actual)),
        ),
        (ExprKind::External(actual), ValueShape::External(signature_shape)) if compatible => Ok(
            ReturnExpr::external_body(primitive::external_return(signature_shape.clone(), actual)),
        ),
        (ExprKind::Float(actual), _) if compatible => {
            Ok(ReturnExpr::float_body(primitive::float_return(actual)))
        }
        (ExprKind::Bool(actual), _) if compatible => {
            Ok(ReturnExpr::bool_body(primitive::bool_return(actual)))
        }
        (ExprKind::Nil(actual), _) if compatible => {
            Ok(ReturnExpr::nil_body(primitive::nil_return(actual)))
        }
        (ExprKind::Tuple(actual), _) if compatible => {
            let type_ = actual.type_().to_vec();
            Ok(ReturnExpr::tuple_body(
                type_,
                primitive::tuple_return(actual),
            ))
        }
        (ExprKind::List(actual), _) if compatible => Ok(list_return_expr(actual)),
        (ExprKind::Function(actual), _) if compatible => {
            Ok(function_value::function_returning_function_expr(actual))
        }
        _ => Err(()),
    };

    return_.map_err(|()| PlanError::InvalidTypedAst {
        reason: InvalidTypedAstReason::FunctionShape {
            name: name.clone(),
            reason: InvalidFunctionShapeReason::ReturnTypeMismatch,
        },
    })
}

fn list_return_expr(actual: ListExpr) -> ReturnExpr {
    match actual {
        ListExpr::Generic(actual) => {
            let parameter = actual.item().parameter();
            ReturnExpr::generic_list_body(parameter, primitive::typed_list_return_body(actual))
        }
        ListExpr::ParameterList(actual) => {
            let parameter = actual.item().parameter();
            ReturnExpr::parameter_list_list_body(
                parameter,
                primitive::typed_list_return_body(actual),
            )
        }
        ListExpr::Int(actual) => {
            ReturnExpr::int_list_body(primitive::typed_list_return_body(actual))
        }
        ListExpr::String(actual) => {
            ReturnExpr::string_list_body(primitive::typed_list_return_body(actual))
        }
        ListExpr::BitArray(actual) => {
            ReturnExpr::bit_array_list_body(primitive::typed_list_return_body(actual))
        }
        ListExpr::UtfCodepoint(actual) => {
            ReturnExpr::utf_codepoint_list_body(primitive::typed_list_return_body(actual))
        }
        ListExpr::Custom(actual) => {
            let item_type = actual.item().item_type();
            ReturnExpr::custom_list_body(item_type, primitive::typed_list_return_body(actual))
        }
        ListExpr::External(actual) => {
            let item_type = actual.item().item_type();
            ReturnExpr::external_list_body(item_type, primitive::typed_list_return_body(actual))
        }
        ListExpr::Float(actual) => {
            ReturnExpr::float_list_body(primitive::typed_list_return_body(actual))
        }
        ListExpr::Bool(actual) => {
            ReturnExpr::bool_list_body(primitive::typed_list_return_body(actual))
        }
        ListExpr::Nil(actual) => {
            ReturnExpr::nil_list_body(primitive::typed_list_return_body(actual))
        }
        ListExpr::Tuple(actual) => {
            let item_type = actual.item().item_type();
            ReturnExpr::tuple_list_body(item_type, primitive::typed_list_return_body(actual))
        }
        ListExpr::List(actual) => {
            let item_shape = actual.item().item_shape().clone();
            ReturnExpr::list_list_body(item_shape, primitive::typed_list_return_body(actual))
        }
        ListExpr::Function(actual) => {
            let item_type = actual.item().item_type();
            ReturnExpr::function_list_body(item_type, primitive::typed_list_return_body(actual))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::function_return_expr;
    use crate::plan::{
        BoolExpr, Expr, FloatExpr, FunctionExpr, FunctionReference, FunctionShape, FunctionType,
        GenericFunctionExpr, GenericFunctionReference, GenericFunctionType, IntExpr,
        IntFunctionExpr, IntFunctionReference, ListExpr, ReturnBody, ReturnExpr, StringExpr,
        TypeParameterId, ValueShape, ValueType, monomorphic_function_instantiation,
    };
    use crate::planner::{InvalidFunctionShapeReason, InvalidTypedAstReason, PlanError};

    #[test]
    fn reject_margin_function_return_family_mismatch() {
        assert_eq!(
            function_return_expr(
                &"main".into(),
                &ValueShape::Float,
                Expr::int(crate::plan::IntExpr::value(1.into())),
            ),
            Err(PlanError::InvalidTypedAst {
                reason: InvalidTypedAstReason::FunctionShape {
                    name: "main".into(),
                    reason: InvalidFunctionShapeReason::ReturnTypeMismatch,
                },
            }),
        );

        assert_eq!(
            function_return_expr(
                &"main".into(),
                &ValueShape::Function(Box::new(FunctionShape::new(Vec::new(), ValueShape::Int,))),
                Expr::function(FunctionExpr::reference(FunctionReference::new(
                    instantiation(FunctionType::new(Vec::new(), ValueType::String))
                ))),
            ),
            Err(PlanError::InvalidTypedAst {
                reason: InvalidTypedAstReason::FunctionShape {
                    name: "main".into(),
                    reason: InvalidFunctionShapeReason::ReturnTypeMismatch,
                },
            }),
        );
    }

    #[test]
    fn reject_margin_function_return_type_metadata_mismatch() {
        let expected = FunctionType::new(Vec::new(), ValueType::Int);
        assert_eq!(
            function_return_expr(
                &"main".into(),
                &ValueShape::Function(Box::new(FunctionShape::from_function_type(expected))),
                Expr::function(FunctionExpr::int(IntFunctionExpr::reference(
                    IntFunctionReference::new(instantiation(FunctionType::new(
                        vec![ValueType::Int],
                        ValueType::Int,
                    ))),
                ))),
            ),
            Err(PlanError::InvalidTypedAst {
                reason: InvalidTypedAstReason::FunctionShape {
                    name: "main".into(),
                    reason: InvalidFunctionShapeReason::ReturnTypeMismatch,
                },
            }),
        );

        let expected = FunctionType::new(vec![ValueType::Int], ValueType::Int);
        assert_eq!(
            function_return_expr(
                &"main".into(),
                &ValueShape::Function(Box::new(FunctionShape::from_function_type(expected))),
                Expr::function(FunctionExpr::int(IntFunctionExpr::reference(
                    IntFunctionReference::new(instantiation(FunctionType::new(
                        Vec::new(),
                        ValueType::Int
                    ))),
                ))),
            ),
            Err(PlanError::InvalidTypedAst {
                reason: InvalidTypedAstReason::FunctionShape {
                    name: "main".into(),
                    reason: InvalidFunctionShapeReason::ReturnTypeMismatch,
                },
            }),
        );
    }

    #[test]
    fn generic_function_returns_preserve_tail_cases_and_block() {
        let parameter = TypeParameterId(0);
        let type_ = GenericFunctionType::new(Vec::new(), parameter);
        let shape = type_.shape();
        let reference = GenericFunctionExpr::reference(
            GenericFunctionReference::new(monomorphic_function_instantiation(0, shape.clone())),
            type_.clone(),
        );
        let call_function = monomorphic_function_instantiation(1, shape.clone());
        let call = GenericFunctionExpr::call(call_function.clone(), Vec::new(), type_.clone());
        let int_case = GenericFunctionExpr::int_case(
            IntExpr::value(0.into()),
            vec![(0.into(), call)],
            reference.clone(),
        )
        .expect("matching generic function types");
        let string_case = GenericFunctionExpr::string_case(
            StringExpr::value("value".into()),
            vec![("value".into(), int_case)],
            reference.clone(),
        )
        .expect("matching generic function types");
        let float_case = GenericFunctionExpr::float_case(
            FloatExpr::value(1.0),
            vec![(1.0, string_case)],
            reference.clone(),
        )
        .expect("matching generic function types");
        let bool_case =
            GenericFunctionExpr::bool_case(BoolExpr::value(true), float_case, reference.clone())
                .expect("matching generic function types");

        assert_eq!(
            function_return_expr(
                &"choose".into(),
                &ValueShape::Function(Box::new(shape.clone())),
                Expr::function(FunctionExpr::generic(GenericFunctionExpr::block(
                    Vec::new(),
                    bool_case,
                ))),
            ),
            Ok(ReturnExpr::generic_function_shape_body(
                shape,
                ReturnBody::block(
                    Vec::new(),
                    ReturnBody::bool_case(
                        BoolExpr::value(true),
                        ReturnBody::float_case(
                            FloatExpr::value(1.0),
                            vec![(
                                1.0,
                                ReturnBody::string_case(
                                    StringExpr::value("value".into()),
                                    vec![(
                                        "value".into(),
                                        ReturnBody::int_case(
                                            IntExpr::value(0.into()),
                                            vec![(
                                                0.into(),
                                                ReturnBody::tail_call(call_function, Vec::new(),),
                                            )],
                                            ReturnBody::expr(reference.clone()),
                                        ),
                                    )],
                                    ReturnBody::expr(reference.clone()),
                                ),
                            )],
                            ReturnBody::expr(reference.clone()),
                        ),
                        ReturnBody::expr(reference),
                    ),
                ),
            )),
        );
    }

    #[test]
    fn plan_list_return_preserves_every_item_family() {
        let string = ListExpr::value(Vec::new(), ValueType::String);
        assert_eq!(
            function_return_expr(
                &"strings".into(),
                &ValueShape::List(Box::new(ValueShape::String)),
                Expr::list(string.clone()),
            ),
            Ok(ReturnExpr::string_list_body(ReturnBody::expr(
                string
                    .into_string()
                    .expect("expression should be List(String)"),
            ),)),
        );

        let bit_array = ListExpr::value(Vec::new(), ValueType::BitArray);
        assert_eq!(
            function_return_expr(
                &"bit_arrays".into(),
                &ValueShape::List(Box::new(ValueShape::BitArray)),
                Expr::list(bit_array.clone()),
            ),
            Ok(ReturnExpr::bit_array_list_body(ReturnBody::expr(
                bit_array
                    .into_bit_array()
                    .expect("expression should be List(BitArray)"),
            ),)),
        );

        let utf_codepoint = ListExpr::value(Vec::new(), ValueType::UtfCodepoint);
        assert_eq!(
            function_return_expr(
                &"utf_codepoints".into(),
                &ValueShape::List(Box::new(ValueShape::UtfCodepoint)),
                Expr::list(utf_codepoint.clone()),
            ),
            Ok(ReturnExpr::utf_codepoint_list_body(ReturnBody::expr(
                utf_codepoint
                    .into_utf_codepoint()
                    .expect("expression should be List(UtfCodepoint)"),
            ),)),
        );

        let float = ListExpr::value(Vec::new(), ValueType::Float);
        assert_eq!(
            function_return_expr(
                &"floats".into(),
                &ValueShape::List(Box::new(ValueShape::Float)),
                Expr::list(float.clone()),
            ),
            Ok(ReturnExpr::float_list_body(ReturnBody::expr(
                float
                    .into_float()
                    .expect("expression should be List(Float)")
            ),)),
        );

        let bool_ = ListExpr::value(Vec::new(), ValueType::Bool);
        assert_eq!(
            function_return_expr(
                &"bools".into(),
                &ValueShape::List(Box::new(ValueShape::Bool)),
                Expr::list(bool_.clone()),
            ),
            Ok(ReturnExpr::bool_list_body(ReturnBody::expr(
                bool_.into_bool().expect("expression should be List(Bool)")
            ),)),
        );

        let nil = ListExpr::value(Vec::new(), ValueType::Nil);
        assert_eq!(
            function_return_expr(
                &"nils".into(),
                &ValueShape::List(Box::new(ValueShape::Nil)),
                Expr::list(nil.clone()),
            ),
            Ok(ReturnExpr::nil_list_body(ReturnBody::expr(
                nil.into_nil().expect("expression should be List(Nil)")
            ),)),
        );

        let tuple_item = vec![ValueType::Int];
        let tuple = ListExpr::value(Vec::new(), ValueType::Tuple(tuple_item.clone()));
        assert_eq!(
            function_return_expr(
                &"tuples".into(),
                &ValueShape::List(Box::new(ValueShape::Tuple(
                    vec![ValueShape::Int].into_boxed_slice(),
                ))),
                Expr::list(tuple.clone()),
            ),
            Ok(ReturnExpr::tuple_list_body(
                tuple_item,
                ReturnBody::expr(
                    tuple
                        .into_tuple()
                        .expect("expression should be List(Tuple)"),
                ),
            )),
        );

        let list_item = Box::new(ValueType::Int);
        let list = ListExpr::value(Vec::new(), ValueType::List(list_item.clone()));
        assert_eq!(
            function_return_expr(
                &"lists".into(),
                &ValueShape::List(Box::new(ValueShape::List(Box::new(ValueShape::Int)))),
                Expr::list(list.clone()),
            ),
            Ok(ReturnExpr::list_list_body(
                crate::plan::ValueStorageShape::Int,
                ReturnBody::expr(list.into_list().expect("expression should be List(List)")),
            )),
        );

        let function_item = FunctionType::new(Vec::new(), ValueType::Int);
        let functions = ListExpr::value(
            Vec::new(),
            ValueType::Function(Box::new(function_item.clone())),
        );
        assert_eq!(
            function_return_expr(
                &"functions".into(),
                &ValueShape::List(Box::new(ValueShape::Function(Box::new(
                    FunctionShape::from_function_type(function_item.clone()),
                )))),
                Expr::list(functions.clone()),
            ),
            Ok(ReturnExpr::function_list_body(
                function_item,
                ReturnBody::expr(
                    functions
                        .into_function()
                        .expect("expression should be List(Function)"),
                ),
            )),
        );

        let int = ListExpr::value(Vec::new(), ValueType::Int);
        assert_eq!(
            function_return_expr(
                &"ints".into(),
                &ValueShape::List(Box::new(ValueShape::Int)),
                Expr::list(int.clone()),
            ),
            Ok(ReturnExpr::int_list_body(ReturnBody::expr(
                int.into_int().expect("expression should be List(Int)")
            ),)),
        );
    }

    fn instantiation(type_: FunctionType) -> crate::plan::FunctionInstantiation {
        monomorphic_function_instantiation(0, FunctionShape::from_function_type(type_))
    }
}