-
Notifications
You must be signed in to change notification settings - Fork 74
/
typecheck.rs
403 lines (377 loc) · 16.3 KB
/
typecheck.rs
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
use crate::data::Value;
use crate::errors::ErrorBuilder;
use crate::lang;
use crate::operator::{
average, count, count_distinct, expr, fields, limit, max, min, parse, percentile, split, sum,
timeslice, total, where_op,
};
use crate::{funcs, operator};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum TypeError {
#[error("Expected boolean expression, found {}", found)]
ExpectedBool { found: String },
#[error("Expected an expression")]
ExpectedExpr,
#[error(
"Wrong number of patterns for parse. Pattern has {} but {} were extracted",
pattern,
extracted
)]
ParseNumPatterns { pattern: usize, extracted: usize },
#[error("Two `from` clauses were provided")]
DoubleFromClause,
#[error("Limit must be a non-zero integer, found {}", limit)]
InvalidLimit { limit: f64 },
#[error("Unknown function {}", name)]
UnknownFunction { name: String },
#[error("Expected a duration for the timeslice (e.g. 1h)")]
ExpectedDuration,
}
pub trait TypeCheck<O> {
fn type_check<E: ErrorBuilder>(self, error_builder: &E) -> Result<O, TypeError>;
}
impl TypeCheck<expr::BoolExpr> for lang::ComparisonOp {
fn type_check<E: ErrorBuilder>(self, _error_builder: &E) -> Result<expr::BoolExpr, TypeError> {
match self {
lang::ComparisonOp::Eq => Ok(expr::BoolExpr::Eq),
lang::ComparisonOp::Neq => Ok(expr::BoolExpr::Neq),
lang::ComparisonOp::Gt => Ok(expr::BoolExpr::Gt),
lang::ComparisonOp::Lt => Ok(expr::BoolExpr::Lt),
lang::ComparisonOp::Gte => Ok(expr::BoolExpr::Gte),
lang::ComparisonOp::Lte => Ok(expr::BoolExpr::Lte),
}
}
}
impl TypeCheck<expr::ArithmeticExpr> for lang::ArithmeticOp {
fn type_check<E: ErrorBuilder>(
self,
_error_builder: &E,
) -> Result<expr::ArithmeticExpr, TypeError> {
match self {
lang::ArithmeticOp::Add => Ok(expr::ArithmeticExpr::Add),
lang::ArithmeticOp::Subtract => Ok(expr::ArithmeticExpr::Subtract),
lang::ArithmeticOp::Multiply => Ok(expr::ArithmeticExpr::Multiply),
lang::ArithmeticOp::Divide => Ok(expr::ArithmeticExpr::Divide),
}
}
}
impl TypeCheck<expr::LogicalExpr> for lang::LogicalOp {
fn type_check<E: ErrorBuilder>(
self,
_error_builder: &E,
) -> Result<expr::LogicalExpr, TypeError> {
match self {
lang::LogicalOp::And => Ok(expr::LogicalExpr::And),
lang::LogicalOp::Or => Ok(expr::LogicalExpr::Or),
}
}
}
impl TypeCheck<operator::Expr> for lang::Expr {
fn type_check<E: ErrorBuilder>(self, error_builder: &E) -> Result<operator::Expr, TypeError> {
match self {
lang::Expr::Column { head, rest } => {
let head = match head {
lang::DataAccessAtom::Key(s) => s,
lang::DataAccessAtom::Index(_) => return Err(TypeError::ExpectedExpr),
};
let rest = rest
.iter()
.map(|s| match s {
lang::DataAccessAtom::Key(s) => expr::ValueRef::Field(s.to_string()),
lang::DataAccessAtom::Index(i) => expr::ValueRef::IndexAt(*i),
})
.collect();
Ok(operator::Expr::NestedColumn { head, rest })
}
lang::Expr::Unary { op, operand } => match op {
lang::UnaryOp::Not => Ok(operator::Expr::BoolUnary(expr::UnaryExpr {
operator: expr::BoolUnaryExpr::Not,
operand: Box::new((*operand).type_check(error_builder)?),
})),
},
lang::Expr::Binary { op, left, right } => match op {
lang::BinaryOp::Comparison(com_op) => {
Ok(operator::Expr::Comparison(expr::BinaryExpr::<
expr::BoolExpr,
> {
left: Box::new((*left).type_check(error_builder)?),
right: Box::new((*right).type_check(error_builder)?),
operator: com_op.type_check(error_builder)?,
}))
}
lang::BinaryOp::Arithmetic(arith_op) => {
Ok(operator::Expr::Arithmetic(expr::BinaryExpr::<
expr::ArithmeticExpr,
> {
left: Box::new((*left).type_check(error_builder)?),
right: Box::new((*right).type_check(error_builder)?),
operator: arith_op.type_check(error_builder)?,
}))
}
lang::BinaryOp::Logical(logical_op) => {
Ok(operator::Expr::Logical(expr::BinaryExpr::<
expr::LogicalExpr,
> {
left: Box::new((*left).type_check(error_builder)?),
right: Box::new((*right).type_check(error_builder)?),
operator: logical_op.type_check(error_builder)?,
}))
}
},
lang::Expr::FunctionCall { name, args } => {
let converted_args: Result<Vec<operator::Expr>, TypeError> = args
.into_iter()
.map(|arg| arg.type_check(error_builder))
.collect();
if let Some(func) = funcs::FUNC_MAP.get(name.as_str()) {
Ok(operator::Expr::FunctionCall {
func,
args: converted_args?,
})
} else {
Err(TypeError::UnknownFunction { name })
}
}
lang::Expr::IfOp {
cond,
value_if_true,
value_if_false,
} => Ok(operator::Expr::IfOp {
cond: Box::new(cond.type_check(error_builder)?),
value_if_true: Box::new(value_if_true.type_check(error_builder)?),
value_if_false: Box::new(value_if_false.type_check(error_builder)?),
}),
lang::Expr::Value(value) => {
let boxed = Box::new(value);
let static_value: &'static mut Value = Box::leak(boxed);
Ok(operator::Expr::Value(static_value))
}
lang::Expr::Error => Err(TypeError::ExpectedExpr),
}
}
}
const DEFAULT_LIMIT: i64 = 10;
impl TypeCheck<Box<dyn operator::OperatorBuilder + Send + Sync>>
for lang::Positioned<lang::InlineOperator>
{
/// Convert the operator syntax to a builder that can instantiate an operator for the
/// pipeline. Any semantic errors in the operator syntax should be detected here.
fn type_check<T: ErrorBuilder>(
self,
error_builder: &T,
) -> Result<Box<dyn operator::OperatorBuilder + Send + Sync>, TypeError> {
match self.value {
lang::InlineOperator::Json { input_column } => Ok(Box::new(parse::ParseJson::new(
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
))),
lang::InlineOperator::Logfmt { input_column } => Ok(Box::new(parse::ParseLogfmt::new(
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
))),
lang::InlineOperator::Parse {
pattern,
fields,
input_column,
no_drop,
} => {
let regex = pattern.to_regex();
let input_column = match input_column {
(Some(from), None) | (None, Some(from)) => Some(from.value),
(None, None) => None,
(Some(l), Some(r)) => {
let e = TypeError::DoubleFromClause;
error_builder
.report_error_for(&e)
.with_code_pointer(&l, "")
.with_code_pointer(&r, "")
.with_resolution("Only one from clause is allowed")
.send_report();
return Err(e);
}
};
if (regex.captures_len() - 1) != fields.len() {
Err(TypeError::ParseNumPatterns {
pattern: regex.captures_len() - 1,
extracted: fields.len(),
})
} else {
Ok(Box::new(parse::Parse::new(
regex,
fields,
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
parse::ParseOptions {
drop_nonmatching: !no_drop,
},
)))
}
}
lang::InlineOperator::Fields { fields, mode } => {
let omode = match mode {
lang::FieldMode::Except => fields::FieldMode::Except,
lang::FieldMode::Only => fields::FieldMode::Only,
};
Ok(Box::new(fields::Fields::new(&fields, omode)))
}
lang::InlineOperator::Where { expr: Some(expr) } => match expr
.value
.type_check(error_builder)?
{
operator::Expr::Value(constant) => {
if let Value::Bool(bool_value) = constant {
Ok(Box::new(where_op::Where::new(*bool_value)))
} else {
let e = TypeError::ExpectedBool {
found: format!("{:?}", constant),
};
error_builder
.report_error_for(&e)
.with_code_range(expr.range, "This is constant")
.with_resolution("Perhaps you meant to compare a field to this value?")
.with_resolution(format!("example: where field1 == {}", constant))
.send_report();
Err(e)
}
}
generic_expr => Ok(Box::new(where_op::Where::new(generic_expr))),
},
lang::InlineOperator::Where { expr: None } => {
let e = TypeError::ExpectedExpr;
error_builder
.report_error_for(&e)
.with_code_pointer(&self, "No condition provided for this 'where'")
.with_resolution(
"Insert an expression whose result determines whether a record should be \
passed downstream",
)
.with_resolution("example: where duration > 100")
.send_report();
Err(e)
}
lang::InlineOperator::Limit { count: Some(count) } => match count.value {
limit if limit.trunc() == 0.0 || limit.fract() != 0.0 => {
let e = TypeError::InvalidLimit { limit };
error_builder
.report_error_for(e.to_string())
.with_code_pointer(
&count,
if limit.fract() != 0.0 {
"Fractional limits are not allowed"
} else {
"Zero is not allowed"
},
)
.with_resolution("Use a positive integer to select the first N rows")
.with_resolution("Use a negative integer to select the last N rows")
.send_report();
Err(e)
}
limit => Ok(Box::new(limit::LimitDef::new(limit as i64))),
},
lang::InlineOperator::Limit { count: None } => {
Ok(Box::new(limit::LimitDef::new(DEFAULT_LIMIT)))
}
lang::InlineOperator::Split {
separator,
input_column,
output_column,
} => Ok(Box::new(split::Split::new(
separator,
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
output_column
.map(|e| e.type_check(error_builder))
.transpose()?,
))),
lang::InlineOperator::Timeslice { duration: None, .. } => {
Err(TypeError::ExpectedDuration)
}
lang::InlineOperator::Timeslice {
input_column,
duration: Some(duration),
output_column,
} => Ok(Box::new(timeslice::Timeslice::new(
input_column.type_check(error_builder)?,
duration,
output_column,
))),
lang::InlineOperator::Total {
input_column,
output_column,
} => Ok(Box::new(total::TotalDef::new(
input_column.type_check(error_builder)?,
output_column,
))),
lang::InlineOperator::FieldExpression { value, name } => Ok(Box::new(
fields::FieldExpressionDef::new(value.type_check(error_builder)?, name),
)),
}
}
}
impl TypeCheck<Box<dyn operator::AggregateFunction>> for lang::Positioned<lang::AggregateFunction> {
fn type_check<T: ErrorBuilder>(
self,
error_builder: &T,
) -> Result<Box<dyn operator::AggregateFunction>, TypeError> {
match self.value {
lang::AggregateFunction::Count { condition } => {
let expr = condition.map(|c| c.type_check(error_builder)).transpose()?;
Ok(Box::new(count::Count::new(expr)))
}
lang::AggregateFunction::Min { column } => {
Ok(Box::new(min::Min::empty(column.type_check(error_builder)?)))
}
lang::AggregateFunction::Average { column } => Ok(Box::new(average::Average::empty(
column.type_check(error_builder)?,
))),
lang::AggregateFunction::Max { column } => {
Ok(Box::new(max::Max::empty(column.type_check(error_builder)?)))
}
lang::AggregateFunction::Sum { column } => {
Ok(Box::new(sum::Sum::empty(column.type_check(error_builder)?)))
}
lang::AggregateFunction::Percentile {
column, percentile, ..
} => Ok(Box::new(percentile::Percentile::empty(
column.type_check(error_builder)?,
percentile,
))),
lang::AggregateFunction::CountDistinct { column: Some(pos) } => {
match pos.value.as_slice() {
[column] => Ok(Box::new(count_distinct::CountDistinct::empty(
column.clone().type_check(error_builder)?,
))),
_ => {
error_builder
.report_error_for("Expecting a single expression to count")
.with_code_pointer(
&pos,
match pos.value.len() {
0 => "No expression given",
_ => "Only a single expression can be given",
},
)
.with_resolution("example: count_distinct(field_to_count)")
.send_report();
Err(TypeError::ExpectedExpr)
}
}
}
lang::AggregateFunction::CountDistinct { column: None } => {
error_builder
.report_error_for("Expecting an expression to count")
.with_code_pointer(&self, "No field argument given")
.with_resolution("example: count_distinct(field_to_count)")
.send_report();
Err(TypeError::ExpectedExpr)
}
lang::AggregateFunction::Error => unreachable!(),
}
}
}