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
use crate::{
    ast::{Expr, MatchPattern, Pattern, RangeInclusion},
    Span, Value, VarId,
};

pub trait Matcher {
    fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool;
}

impl Matcher for MatchPattern {
    fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool {
        self.pattern.match_value(value, matches)
    }
}

impl Matcher for Pattern {
    fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool {
        match self {
            Pattern::Garbage => false,
            Pattern::IgnoreValue => true,
            Pattern::IgnoreRest => false, // `..` and `..$foo` only match in specific contexts
            Pattern::Rest(_) => false,    // so we return false here and handle them elsewhere
            Pattern::Record(field_patterns) => match value {
                Value::Record { val, .. } => {
                    'top: for field_pattern in field_patterns {
                        for (col, val) in &**val {
                            if col == &field_pattern.0 {
                                // We have found the field
                                let result = field_pattern.1.match_value(val, matches);
                                if !result {
                                    return false;
                                } else {
                                    continue 'top;
                                }
                            }
                        }
                        return false;
                    }
                    true
                }
                _ => false,
            },
            Pattern::Variable(var_id) => {
                // TODO: FIXME: This needs the span of this variable
                matches.push((*var_id, value.clone()));
                true
            }
            Pattern::List(items) => match &value {
                Value::List { vals, .. } => {
                    if items.len() > vals.len() {
                        // The only we we allow this is to have a rest pattern in the n+1 position
                        if items.len() == (vals.len() + 1) {
                            match &items[vals.len()].pattern {
                                Pattern::IgnoreRest => {}
                                Pattern::Rest(var_id) => {
                                    matches.push((*var_id, Value::nothing(items[vals.len()].span)))
                                }
                                _ => {
                                    // There is a pattern which can't skip missing values, so we fail
                                    return false;
                                }
                            }
                        } else {
                            // There are patterns that can't be matches, so we fail
                            return false;
                        }
                    }
                    for (val_idx, val) in vals.iter().enumerate() {
                        // We require that the pattern and the value have the same number of items, or the pattern does not match
                        // The only exception is if the pattern includes a `..` pattern
                        if let Some(pattern) = items.get(val_idx) {
                            match &pattern.pattern {
                                Pattern::IgnoreRest => {
                                    break;
                                }
                                Pattern::Rest(var_id) => {
                                    let rest_vals = vals[val_idx..].to_vec();
                                    matches.push((*var_id, Value::list(rest_vals, pattern.span)));
                                    break;
                                }
                                _ => {
                                    if !pattern.match_value(val, matches) {
                                        return false;
                                    }
                                }
                            }
                        } else {
                            return false;
                        }
                    }

                    true
                }
                _ => false,
            },
            Pattern::Value(pattern_value) => {
                // TODO: Fill this out with the rest of them
                match &pattern_value.expr {
                    Expr::Nothing => {
                        matches!(value, Value::Nothing { .. })
                    }
                    Expr::Int(x) => {
                        if let Value::Int { val, .. } = &value {
                            x == val
                        } else {
                            false
                        }
                    }
                    Expr::Float(x) => {
                        if let Value::Float { val, .. } = &value {
                            x == val
                        } else {
                            false
                        }
                    }
                    Expr::Binary(x) => {
                        if let Value::Binary { val, .. } = &value {
                            x == val
                        } else {
                            false
                        }
                    }
                    Expr::Bool(x) => {
                        if let Value::Bool { val, .. } = &value {
                            x == val
                        } else {
                            false
                        }
                    }
                    Expr::String(x) => {
                        if let Value::String { val, .. } = &value {
                            x == val
                        } else {
                            false
                        }
                    }
                    Expr::DateTime(x) => {
                        if let Value::Date { val, .. } = &value {
                            x == val
                        } else {
                            false
                        }
                    }
                    Expr::ValueWithUnit(val) => {
                        let span = val.unit.span;

                        if let Expr::Int(size) = val.expr.expr {
                            match &val.unit.item.build_value(size, span) {
                                Ok(v) => v == value,
                                _ => false,
                            }
                        } else {
                            false
                        }
                    }
                    Expr::Range(range) => {
                        // TODO: Add support for floats

                        let start = if let Some(start) = &range.from {
                            match &start.expr {
                                Expr::Int(start) => *start,
                                _ => return false,
                            }
                        } else {
                            0
                        };

                        let end = if let Some(end) = &range.to {
                            match &end.expr {
                                Expr::Int(end) => *end,
                                _ => return false,
                            }
                        } else {
                            i64::MAX
                        };

                        let step = if let Some(step) = &range.next {
                            match &step.expr {
                                Expr::Int(step) => *step - start,
                                _ => return false,
                            }
                        } else if end < start {
                            -1
                        } else {
                            1
                        };

                        let (start, end) = if end < start {
                            (end, start)
                        } else {
                            (start, end)
                        };

                        if let Value::Int { val, .. } = &value {
                            if matches!(range.operator.inclusion, RangeInclusion::RightExclusive) {
                                *val >= start && *val < end && ((*val - start) % step) == 0
                            } else {
                                *val >= start && *val <= end && ((*val - start) % step) == 0
                            }
                        } else {
                            false
                        }
                    }
                    _ => false,
                }
            }
            Pattern::Or(patterns) => {
                let mut result = false;

                for pattern in patterns {
                    let mut local_matches = vec![];
                    if !result {
                        if pattern.match_value(value, &mut local_matches) {
                            // TODO: do we need to replace previous variables that defaulted to nothing?
                            matches.append(&mut local_matches);
                            result = true;
                        } else {
                            // Create variables that don't match and assign them to null
                            let vars = pattern.variables();
                            for var in &vars {
                                let mut found = false;
                                for match_ in matches.iter() {
                                    if match_.0 == *var {
                                        found = true;
                                    }
                                }

                                if !found {
                                    // FIXME: don't use Span::unknown()
                                    matches.push((*var, Value::nothing(Span::unknown())))
                                }
                            }
                        }
                    } else {
                        // We already have a match, so ignore the remaining match variables
                        // And assign them to null
                        let vars = pattern.variables();
                        for var in &vars {
                            let mut found = false;
                            for match_ in matches.iter() {
                                if match_.0 == *var {
                                    found = true;
                                }
                            }

                            if !found {
                                // FIXME: don't use Span::unknown()
                                matches.push((*var, Value::nothing(Span::unknown())))
                            }
                        }
                    }
                }
                result
            }
        }
    }
}