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
use {
	super::{Ingredient, Method, Recipe, RecipeError, RecipeUtilities},
	crate::{executor::types::Row, Result, Value},
};

#[derive(Clone)]
pub enum SimplifyBy<'a> {
	Basic,
	OptRow(&'a Vec<Option<Value>>),
	Row(&'a Row),
	CompletedAggregate(Vec<Value>),
}

pub trait Resolve
where
	Self: Sized,
{
	fn simplify(self, component: SimplifyBy) -> Result<Self>;
}

impl Resolve for Recipe {
	fn simplify(self, component: SimplifyBy) -> Result<Self> {
		match self {
			Recipe::Ingredient(ingredient) => {
				ingredient.simplify(component).map(Recipe::Ingredient)
			}
			Recipe::Method(method) => method.simplify(component).map(|method| {
				if let Method::Value(value) = method {
					Recipe::Ingredient(Ingredient::Value(value))
				} else {
					Recipe::Method(Box::new(method))
				}
			}),
		}
	}
}

impl Resolve for Ingredient {
	fn simplify(self, component: SimplifyBy) -> Result<Self> {
		Ok(match self {
			Ingredient::Column(index) => {
				if let SimplifyBy::Row(row) = component {
					Ingredient::Value(row.get(index).ok_or(RecipeError::UnreachableNoRow)?.clone())
				} else if let SimplifyBy::OptRow(row) = component {
					row.get(index)
						.and_then(Clone::clone)
						.map(Ingredient::Value)
						.unwrap_or(self)
				} else {
					self
				}
			}
			Ingredient::Aggregate(index) => {
				if let SimplifyBy::CompletedAggregate(values) = component {
					Ingredient::Value(values.get(index).ok_or(RecipeError::Unreachable)?.clone())
				} else {
					self
				}
			}
			Ingredient::Value(..) => self, // Already simple!
		})
	}
}

#[allow(clippy::if_same_then_else)] // No idea what Clippy is trying to say here
#[allow(clippy::collapsible_else_if)] // Intentional for clarity
impl Resolve for Method {
	fn simplify(self, component: SimplifyBy) -> Result<Self> {
		Ok(match self {
			Method::UnaryOperation(operator, recipe) => {
				let recipe = recipe.simplify(component)?;
				if let Some(value) = recipe.as_solution() {
					Method::Value(operator(value)?)
				} else {
					Method::UnaryOperation(operator, recipe)
				}
			}
			Method::BinaryOperation(operator, left, right) => {
				let left = left.simplify(component.clone())?;

				if let Some(Value::Bool(value)) = left.as_solution() {
					// Optimisation -- is this a good idea?
					if !value {
						// Clippy didn't like this without "as usize"
						if operator as usize == Value::and as usize {
							return Ok(Method::Value(Value::Bool(false)));
						}
					} else {
						if operator as usize == Value::or as usize {
							return Ok(Method::Value(Value::Bool(true)));
						}
					}
				}

				let right = right.simplify(component)?;

				if let (Some(left), Some(right)) = (left.as_solution(), right.as_solution()) {
					Method::Value(operator(left, right)?)
				} else {
					Method::BinaryOperation(operator, left, right)
				}
			}
			Method::Function(function, arguments) => {
				let arguments = arguments
					.into_iter()
					.map(|argument| argument.simplify(component.clone()))
					.collect::<Result<Vec<Recipe>>>()?;
				if let Some(arguments) = arguments
					.iter()
					.map(|argument| argument.as_solution())
					.collect::<Option<Vec<Value>>>()
				{
					Method::Value(function(arguments)?)
				} else {
					Method::Function(function, arguments)
				}
			}
			Method::Cast(data_type, recipe) => {
				let recipe = recipe.simplify(component)?;
				if let Some(value) = recipe.as_solution() {
					Method::Value(value.cast_datatype(&data_type)?)
				} else {
					Method::Cast(data_type, recipe)
				}
			}

			Method::Case {
				operand,
				cases,
				else_result,
			} => {
				let operand = operand
					.map(|operand| operand.simplify(component.clone()))
					.transpose()?;
				let else_result = else_result
					.map(|else_result| else_result.simplify(component.clone()))
					.transpose()?;
				let cases = cases
					.into_iter()
					.map(|(condition, result)| {
						Ok((
							condition.simplify(component.clone())?,
							result.simplify(component.clone())?,
						))
					})
					.collect::<Result<Vec<(Recipe, Recipe)>>>()?;

				if let Some(None) = operand.clone().map(|operand| operand.as_solution()) {
					Method::Case {
						operand,
						cases,
						else_result,
					}
				} else if let Some(None) = else_result
					.clone()
					.map(|else_result| else_result.as_solution())
				{
					Method::Case {
						operand,
						cases,
						else_result,
					}
				} else if let Some(cases) = cases
					.iter()
					.map(|(condition, result)| {
						Some((condition.as_solution()?, result.as_solution()?))
					})
					.collect::<Option<Vec<(Value, Value)>>>()
				{
					let operand = operand.map(|operand| operand.as_solution());
					let else_result = else_result
						.map(|else_result| else_result.as_solution())
						.unwrap_or(Some(Value::Null))
						.unwrap();
					if let Some(operand) = operand {
						let operand = operand.unwrap();
						Method::Value(
							cases
								.into_iter()
								.find_map(|(condition, result)| {
									if operand == condition {
										Some(result)
									} else {
										None
									}
								})
								.unwrap_or(else_result),
						)
					} else {
						Method::Value(
							cases
								.into_iter()
								.find_map(|(condition, result)| {
									if matches!(condition, Value::Bool(true)) {
										Some(result)
									} else {
										None
									}
								})
								.unwrap_or(else_result),
						)
					}
				} else {
					Method::Case {
						operand,
						cases,
						else_result,
					}
				}
			}

			Method::Value(..) => return Err(RecipeError::Unreachable.into()),

			// This will only occur for a special aggregate simplify
			Method::Aggregate(operator, recipe) => {
				Method::Aggregate(operator, recipe.simplify(component)?)
			}
		})
	}
}