ryan 0.2.3

Ryan: a configuration language for the practical programmer
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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use std::{
    cmp,
    collections::HashMap,
    error::Error,
    fmt::{self, Debug, Display},
    rc::Rc,
};
use thiserror::Error;

use crate::{
    parser::{NotIterable, Pattern, TypeExpression, Value},
    rc_world,
};

/// A native pattern match. It matches a Ryan value to a given pattern and, if there is
/// a match, applies a supplied closure to the value. Use this type to create your own
/// extensions and built-in functions to Ryan.
pub struct NativePatternMatch {
    /// The name by which users will call this pattern match in their code.
    pub identifier: Rc<str>,
    /// The pattern to which input values must comply to.
    pub pattern: Pattern,
    /// The native function mapping the input value to the output value.
    pub func: Box<dyn Fn(Value) -> Result<Value, Box<dyn Error + 'static>>>,
}

impl Display for NativePatternMatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "![native pattern {} {}]", self.identifier, self.pattern)
    }
}

impl Debug for NativePatternMatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.to_string())
    }
}

impl PartialEq for NativePatternMatch {
    fn eq(&self, other: &Self) -> bool {
        self.identifier == other.identifier && self.pattern == other.pattern
    }
}

impl NativePatternMatch {
    /// Creates a new native pattern match given a name, a pattern and a mapping function.
    pub fn new<F, E>(name: &str, pattern: Pattern, f: F) -> NativePatternMatch
    where
        F: 'static + Fn(Value) -> Result<Value, E>,
        E: 'static + Error,
    {
        NativePatternMatch {
            identifier: rc_world::str_to_rc(name),
            pattern,
            func: Box::new(move |v| f(v).map_err(|e| Box::new(e).into())),
        }
    }
}

/// A wrapper around a string that implements [`Error`]. Use this type to conveniently
/// throw log-and-forget errors from your extensions.
#[derive(Debug, Error)]
pub struct BuiltinErrorMsg(String);

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

fn build_built_ins() -> HashMap<Rc<str>, Value> {
    let mut built_ins = HashMap::new();

    fn t(s: &str) -> Rc<str> {
        rc_world::str_to_rc(s)
    }

    let mut insert = |pat: NativePatternMatch| {
        built_ins.insert(
            pat.identifier.clone(),
            Value::NativePatternMatch(pat.into()),
        )
    };

    insert(NativePatternMatch::new(
        "fmt",
        Pattern::Identifier(t("x"), None),
        move |value| {
            Ok(Value::Text(rc_world::string_to_rc(value.to_string()))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "len",
        Pattern::Identifier(t("x"), None),
        move |value| {
            let len = match value {
                Value::List(list) => list.len() as i64,
                Value::Map(map) => map.len() as i64,
                Value::Text(text) => text.len() as i64,
                _ => return Err(BuiltinErrorMsg(format!("Value `{value}` has no length"))),
            };

            Ok(Value::Integer(len))
        },
    ));
    insert(NativePatternMatch::new(
        "range",
        Pattern::MatchList(vec![
            Pattern::Identifier(t("start"), None),
            Pattern::Identifier(t("end"), None),
        ]),
        move |value| match value {
            Value::List(range) => match &*range {
                [Value::Integer(start), Value::Integer(end)] => {
                    Ok(Value::List((*start..*end).map(Value::Integer).collect()))
                }
                bad => Err(BuiltinErrorMsg(format!("List `{bad:?}` cannot be a range"))),
            },
            _ => Err(BuiltinErrorMsg(format!(
                "Value `{value}` cannot be a range"
            ))),
        },
    ));
    insert(NativePatternMatch::new(
        "zip",
        Pattern::MatchList(vec![
            Pattern::Identifier(t("left"), None),
            Pattern::Identifier(t("right"), None),
        ]),
        move |value| {
            let Value::List(list) = value else {
                unreachable!()
            };
            let [left, right] = &*list else {
                unreachable!()
            };

            let zipped: Value = left
                .iter()?
                .zip(right.iter()?)
                .map(|(left, right)| Value::List(vec![left, right].into()))
                .collect();

            Ok(zipped) as Result<_, NotIterable>
        },
    ));
    insert(NativePatternMatch::new(
        "enumerate",
        Pattern::Identifier(t("x"), None),
        move |value| {
            let enumerated: Value = value
                .iter()?
                .enumerate()
                .map(|(i, val)| Value::List(vec![Value::Integer(i as i64), val].into()))
                .collect();
            Ok(enumerated) as Result<_, NotIterable>
        },
    ));
    insert(NativePatternMatch::new(
        "sum",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::List(Box::new(TypeExpression::Or(vec![
                TypeExpression::Float,
                TypeExpression::Integer,
            ])))),
        ),
        move |value| {
            let mut sum = Value::Integer(0);

            for val in value.iter()? {
                sum = match (val, sum) {
                    (Value::Integer(val), Value::Integer(sum)) => Value::Integer(val + sum),
                    (Value::Float(val), Value::Integer(sum)) => Value::Float(val + sum as f64),
                    (Value::Integer(val), Value::Float(sum)) => Value::Float(val as f64 + sum),
                    (Value::Float(val), Value::Float(sum)) => Value::Float(val + sum),
                    _ => unreachable!(),
                }
            }

            Ok(sum) as Result<_, NotIterable>
        },
    ));
    insert(NativePatternMatch::new(
        "max",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::List(Box::new(TypeExpression::Or(vec![
                TypeExpression::Float,
                TypeExpression::Integer,
            ])))),
        ),
        move |value| {
            let mut max = Value::Integer(0);

            for val in value.iter()? {
                max = match (val, max) {
                    (Value::Integer(val), Value::Integer(max)) => {
                        Value::Integer(i64::max(val, max))
                    }
                    (Value::Float(val), Value::Integer(max)) => {
                        Value::Float(f64::max(val, max as f64))
                    }
                    (Value::Integer(val), Value::Float(max)) => {
                        Value::Float(f64::max(val as f64, max))
                    }
                    (Value::Float(val), Value::Float(max)) => Value::Float(f64::max(val, max)),
                    _ => unreachable!(),
                }
            }

            Ok(max) as Result<_, NotIterable>
        },
    ));
    insert(NativePatternMatch::new(
        "min",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::List(Box::new(TypeExpression::Or(vec![
                TypeExpression::Float,
                TypeExpression::Integer,
            ])))),
        ),
        move |value| {
            let mut min = Value::Integer(0);

            for val in value.iter()? {
                min = match (val, min) {
                    (Value::Integer(val), Value::Integer(min)) => {
                        Value::Integer(i64::min(val, min))
                    }
                    (Value::Float(val), Value::Integer(min)) => {
                        Value::Float(f64::min(val, min as f64))
                    }
                    (Value::Integer(val), Value::Float(min)) => {
                        Value::Float(f64::min(val as f64, min))
                    }
                    (Value::Float(val), Value::Float(min)) => Value::Float(f64::min(val, min)),
                    _ => unreachable!(),
                }
            }

            Ok(min) as Result<_, NotIterable>
        },
    ));
    insert(NativePatternMatch::new(
        "all",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::List(Box::new(TypeExpression::Or(vec![
                TypeExpression::Bool,
            ])))),
        ),
        move |value| {
            for val in value.iter()? {
                if let Value::Bool(false) = val {
                    return Ok(Value::Bool(false));
                }
            }

            Ok(Value::Bool(true)) as Result<_, NotIterable>
        },
    ));
    insert(NativePatternMatch::new(
        "any",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::List(Box::new(TypeExpression::Or(vec![
                TypeExpression::Bool,
            ])))),
        ),
        move |value| {
            for val in value.iter()? {
                if let Value::Bool(true) = val {
                    return Ok(Value::Bool(true));
                }
            }

            Ok(Value::Bool(false)) as Result<_, NotIterable>
        },
    ));

    #[derive(Debug, Error)]
    #[error("Value {a} cannot be compared with {b}")]
    struct NotComparable {
        a: Value,
        b: Value,
    }

    insert(NativePatternMatch::new(
        "sort",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::List(Box::new(TypeExpression::Any))),
        ),
        move |value| {
            let Value::List(list) = value else {
                unreachable!()
            };
            let mut list = list.to_vec();
            let mut bad_comp = None;
            list.sort_by(|a, b| {
                if let Some(cmp) = a.partial_cmp(b) {
                    cmp
                } else {
                    bad_comp = Some(NotComparable {
                        a: a.clone(),
                        b: b.clone(),
                    });
                    cmp::Ordering::Greater
                }
            });

            if let Some(error) = bad_comp {
                Err(error)
            } else {
                Ok(Value::List(list.into()))
            }
        },
    ));
    insert(NativePatternMatch::new(
        "keys",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::Dictionary(Box::new(TypeExpression::Any))),
        ),
        move |value| {
            let Value::Map(dict) = value else {
                unreachable!()
            };
            let keys: Vec<_> = dict
                .keys()
                .map(|key| Value::Text(rc_world::str_to_rc(key)))
                .collect();

            Ok(Value::List(keys.into())) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "values",
        Pattern::Identifier(
            t("x"),
            Some(TypeExpression::Dictionary(Box::new(TypeExpression::Any))),
        ),
        move |value| {
            let Value::Map(dict) = value else {
                unreachable!()
            };
            let keys: Vec<_> = dict.values().cloned().collect();

            Ok(Value::List(keys.into())) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "join",
        Pattern::Identifier(t("sep"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(separator) = value else {
                unreachable!()
            };

            Ok(Value::NativePatternMatch(Rc::new(NativePatternMatch::new(
                "join$ret",
                Pattern::Identifier(
                    t("x"),
                    Some(TypeExpression::List(Box::new(TypeExpression::Text))),
                ),
                move |value| {
                    let mut iter = value.iter()?;
                    let mut string = String::new();

                    if let Some(val) = iter.next() {
                        let Value::Text(text) = val else {
                            unreachable!()
                        };
                        string += text.as_ref();
                    }

                    for val in iter {
                        let Value::Text(text) = val else {
                            unreachable!()
                        };
                        string += &*separator;
                        string += &*text;
                    }

                    Ok(Value::Text(rc_world::string_to_rc(string))) as Result<_, NotIterable>
                },
            )))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "split",
        Pattern::Identifier(t("sep"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(separator) = value else {
                unreachable!()
            };

            Ok(Value::NativePatternMatch(Rc::new(NativePatternMatch::new(
                "split$ret",
                Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
                move |value| {
                    let Value::Text(text) = value else {
                        unreachable!()
                    };

                    let split: Vec<_> = text
                        .split(&*separator)
                        .map(|part| Value::Text(rc_world::str_to_rc(part)))
                        .collect();
                    Ok(Value::List(split.into())) as Result<_, NotIterable>
                },
            )))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "trim",
        Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(text) = value else {
                unreachable!()
            };

            Ok(Value::Text(rc_world::str_to_rc(
                text.trim_start().trim_end(),
            ))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "trim_start",
        Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(text) = value else {
                unreachable!()
            };

            Ok(Value::Text(rc_world::str_to_rc(text.trim_start()))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "trim_end",
        Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(text) = value else {
                unreachable!()
            };

            Ok(Value::Text(rc_world::str_to_rc(text.trim_end()))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "starts_with",
        Pattern::Identifier(t("prefix"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(prefix) = value else {
                unreachable!()
            };

            Ok(Value::NativePatternMatch(Rc::new(NativePatternMatch::new(
                "starts_with$ret",
                Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
                move |value| {
                    let Value::Text(text) = value else {
                        unreachable!()
                    };

                    let starts_with = text.starts_with(&*prefix);
                    Ok(Value::Bool(starts_with)) as Result<_, NotIterable>
                },
            )))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "ends_with",
        Pattern::Identifier(t("postfix"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(postfix) = value else {
                unreachable!()
            };

            Ok(Value::NativePatternMatch(Rc::new(NativePatternMatch::new(
                "ends_with$ret",
                Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
                move |value| {
                    let Value::Text(text) = value else {
                        unreachable!()
                    };

                    let starts_with = text.ends_with(&*postfix);
                    Ok(Value::Bool(starts_with)) as Result<_, NotIterable>
                },
            )))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "lowercase",
        Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(text) = value else {
                unreachable!()
            };

            Ok(Value::Text(rc_world::string_to_rc(text.to_lowercase())))
                as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "uppercase",
        Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(text) = value else {
                unreachable!()
            };

            Ok(Value::Text(rc_world::string_to_rc(text.to_uppercase())))
                as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "replace",
        Pattern::MatchList(vec![
            Pattern::Identifier(t("find"), Some(TypeExpression::Text)),
            Pattern::Identifier(t("subst"), Some(TypeExpression::Text)),
        ]),
        move |value| {
            let Value::List(list) = value else {
                unreachable!()
            };
            let [Value::Text(find), Value::Text(subst)] = &*list else {
                unreachable!()
            };
            let find = find.clone();
            let subst = subst.clone();

            Ok(Value::NativePatternMatch(Rc::new(NativePatternMatch::new(
                "replace$ret",
                Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
                move |value| {
                    let Value::Text(text) = value else {
                        unreachable!()
                    };

                    let replaced = text.replace(find.as_ref(), &subst);
                    Ok(Value::Text(rc_world::string_to_rc(replaced))) as Result<_, NotIterable>
                },
            )))) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "parse_int",
        Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(int) = value else {
                unreachable!()
            };

            Ok(Value::Integer(
                int.parse::<i64>()
                    .map_err(|err| BuiltinErrorMsg(err.to_string()))?,
            )) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "parse_float",
        Pattern::Identifier(t("x"), Some(TypeExpression::Text)),
        move |value| {
            let Value::Text(int) = value else {
                unreachable!()
            };

            Ok(Value::Float(
                int.parse::<f64>()
                    .map_err(|err| BuiltinErrorMsg(err.to_string()))?,
            )) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "floor",
        Pattern::Identifier(t("x"), Some(TypeExpression::Float)),
        move |value| {
            let Value::Float(float) = value else {
                unreachable!()
            };

            Ok(Value::Float(float.floor())) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "ceil",
        Pattern::Identifier(t("x"), Some(TypeExpression::Float)),
        move |value| {
            let Value::Float(float) = value else {
                unreachable!()
            };

            Ok(Value::Float(float.ceil())) as Result<_, BuiltinErrorMsg>
        },
    ));
    insert(NativePatternMatch::new(
        "round",
        Pattern::Identifier(t("x"), Some(TypeExpression::Float)),
        move |value| {
            let Value::Float(float) = value else {
                unreachable!()
            };

            Ok(Value::Float(float.round())) as Result<_, BuiltinErrorMsg>
        },
    ));

    built_ins
}

thread_local! {
    /// The Ryan default built_ins that are supplied as "batteries included". All default
    /// built_ins are guaranteed to finish executing and to not access the outside
    /// environment, in compliance to Ryan's key principles.
    pub static BUILT_INS: Rc<HashMap<Rc<str>, Value>> = Rc::new(build_built_ins());
}