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
use super::*;

/// Utility struct for the `when-then-otherwise` expression.
///
/// Represents the state of the expression after [when] is called.
///
/// In this state, `then` must be called to continue to finish the expression.
#[derive(Clone)]
pub struct When {
    condition: Expr,
}

/// Utility struct for the `when-then-otherwise` expression.
///
/// Represents the state of the expression after `when(...).then(...)` is called.
#[derive(Clone)]
pub struct Then {
    condition: Expr,
    statement: Expr,
}

/// Utility struct for the `when-then-otherwise` expression.
///
/// Represents the state of the expression after an additional `when` is called.
///
/// In this state, `then` must be called to continue to finish the expression.
#[derive(Clone)]
pub struct ChainedWhen {
    conditions: Vec<Expr>,
    statements: Vec<Expr>,
}

/// Utility struct for the `when-then-otherwise` expression.
///
/// Represents the state of the expression after an additional `then` is called.
#[derive(Clone)]
pub struct ChainedThen {
    conditions: Vec<Expr>,
    statements: Vec<Expr>,
}

impl When {
    /// Add a condition to the `when-then-otherwise` expression.
    pub fn then<E: Into<Expr>>(self, expr: E) -> Then {
        Then {
            condition: self.condition,
            statement: expr.into(),
        }
    }
}

impl Then {
    /// Attach a statement to the corresponding condition.
    pub fn when<E: Into<Expr>>(self, condition: E) -> ChainedWhen {
        ChainedWhen {
            conditions: vec![self.condition, condition.into()],
            statements: vec![self.statement],
        }
    }

    /// Define a default for the `when-then-otherwise` expression.
    pub fn otherwise<E: Into<Expr>>(self, statement: E) -> Expr {
        ternary_expr(self.condition, self.statement, statement.into())
    }
}

impl ChainedWhen {
    pub fn then<E: Into<Expr>>(mut self, statement: E) -> ChainedThen {
        self.statements.push(statement.into());
        ChainedThen {
            conditions: self.conditions,
            statements: self.statements,
        }
    }
}

impl ChainedThen {
    /// Add another condition to the `when-then-otherwise` expression.
    pub fn when<E: Into<Expr>>(mut self, condition: E) -> ChainedWhen {
        self.conditions.push(condition.into());

        ChainedWhen {
            conditions: self.conditions,
            statements: self.statements,
        }
    }

    /// Define a default for the `when-then-otherwise` expression.
    pub fn otherwise<E: Into<Expr>>(self, expr: E) -> Expr {
        // we iterate the preds/ exprs last in first out
        // and nest them.
        //
        // // this expr:
        //   when((col('x') == 'a')).then(1)
        //         .when(col('x') == 'b').then(2)
        //         .when(col('x') == 'c').then(3)
        //         .otherwise(4)
        //
        // needs to become:
        //       when((col('x') == 'a')).then(1)                        -
        //         .otherwise(                                           |
        //             when(col('x') == 'b').then(2)            -        |
        //             .otherwise(                               |       |
        //                 pl.when(col('x') == 'c').then(3)      |       |
        //                 .otherwise(4)                         | inner | outer
        //             )                                         |       |
        //         )                                            _|      _|
        //
        // by iterating LIFO we first create
        // `inner` and then assign that to `otherwise`,
        // which will be used in the next layer `outer`
        //

        let conditions_iter = self.conditions.into_iter().rev();
        let mut statements_iter = self.statements.into_iter().rev();

        let mut otherwise = expr.into();

        for e in conditions_iter {
            otherwise = ternary_expr(
                e,
                statements_iter
                    .next()
                    .expect("expr expected, did you call when().then().otherwise?"),
                otherwise,
            );
        }

        otherwise
    }
}

/// Start a `when-then-otherwise` expression.
pub fn when<E: Into<Expr>>(condition: E) -> When {
    When {
        condition: condition.into(),
    }
}

pub fn ternary_expr(predicate: Expr, truthy: Expr, falsy: Expr) -> Expr {
    Expr::Ternary {
        predicate: Arc::new(predicate),
        truthy: Arc::new(truthy),
        falsy: Arc::new(falsy),
    }
}

/// Compute `op(l, r)` (or equivalently `l op r`). `l` and `r` must have types compatible with the Operator.
pub fn binary_expr(l: Expr, op: Operator, r: Expr) -> Expr {
    Expr::BinaryExpr {
        left: Arc::new(l),
        op,
        right: Arc::new(r),
    }
}