Skip to main content

tancore/
cmp.rs

1use std::cmp::Ordering;
2
3use tan::{
4    context::Context,
5    expr::{annotate_type, Expr},
6    util::module_util::require_module,
7};
8
9use super::{arithmetic, string::string_compare};
10
11pub fn rust_ordering_from_tan_ordering(tan_ordering: &Expr) -> Option<Ordering> {
12    let ordering = tan_ordering.as_int()?;
13    Some(ordering.cmp(&0))
14}
15
16pub fn setup_lib_cmp(context: &mut Context) {
17    let module = require_module("prelude", context);
18
19    // cmp
20
21    // #todo `eq` and `Comparable` are related.
22    // #todo consider to make sorter: `cmp`.
23
24    module.insert_invocable("compare", Expr::foreign_func(&arithmetic::int_compare));
25    module.insert_invocable(
26        "compare$$Int$$Int",
27        annotate_type(Expr::foreign_func(&arithmetic::int_compare), "Int"),
28    );
29    module.insert_invocable(
30        "compare$$String$$String",
31        annotate_type(Expr::foreign_func(&string_compare), "String"),
32    );
33}
34
35#[cfg(test)]
36mod tests {
37    use std::cmp::Ordering;
38
39    use assert_matches::assert_matches;
40
41    use tan::expr::Expr;
42
43    use crate::cmp::rust_ordering_from_tan_ordering;
44
45    #[test]
46    fn rust_ordering_from_tan_ordering_usage() {
47        assert_matches!(
48            rust_ordering_from_tan_ordering(&Expr::Int(20)),
49            Some(Ordering::Greater)
50        );
51        assert_matches!(
52            rust_ordering_from_tan_ordering(&Expr::Int(0)),
53            Some(Ordering::Equal)
54        );
55    }
56}