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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
use vec::{vector, label_name, Vector};
use str::string;
use nom::{
	recognize_float,
	IResult,
};
use nom::types::CompleteByteSlice;

/// PromQL operators
#[derive(Debug, PartialEq)]
pub enum Op {
	/** `^` */ Pow(Option<OpMod>),

	/** `*` */ Mul(Option<OpMod>),
	/** `/` */ Div(Option<OpMod>),
	/** `%` */ Mod(Option<OpMod>),

	/** `+` */ Plus(Option<OpMod>),
	/** `-` */ Minus(Option<OpMod>),

	/// `==`, with optional `bool` modifier in addition to regular operator modifiers
	Eq(bool, Option<OpMod>),
	/// `!=`, with optional `bool` modifier in addition to regular operator modifiers
	Ne(bool, Option<OpMod>),
	/// `<`, with optional `bool` modifier in addition to regular operator modifiers
	Lt(bool, Option<OpMod>),
	/// `>`, with optional `bool` modifier in addition to regular operator modifiers
	Gt(bool, Option<OpMod>),
	/// `<=`, with optional `bool` modifier in addition to regular operator modifiers
	Le(bool, Option<OpMod>),
	/// `>=`, with optional `bool` modifier in addition to regular operator modifiers
	Ge(bool, Option<OpMod>),

	/** `and` */ And(Option<OpMod>),
	/** `unless` */ Unless(Option<OpMod>),

	/** `or` */ Or(Option<OpMod>),
}

#[derive(Debug, PartialEq)]
pub enum OpModAction { RestrictTo, Ignore }
/// Vector matching operator modifier (`on (…)`/`ignoring (…)`).
#[derive(Debug, PartialEq)]
pub struct OpMod {
	/// Action applied to a list of vectors; whether `on (…)` or `ignored(…)` is used after the operator.
	pub action: OpModAction,
	/// Set of labels to apply `action` to.
	pub labels: Vec<String>,
	/// Additional grouping modifier, if any.
	pub group: Option<OpGroupMod>,
}

#[derive(Debug, PartialEq)]
pub enum OpGroupSide { Left, Right }
/// Vector grouping operator modifier (`group_left(…)`/`group_right(…)`).
#[derive(Debug, PartialEq)]
pub struct OpGroupMod {
	pub side: OpGroupSide,
	pub labels: Vec<String>,
}

#[derive(Debug, PartialEq)]
pub enum AggregationAction { Without, By }
#[derive(Debug, PartialEq)]
pub struct AggregationMod {
	// Action applied to a list of vectors; whether `by (…)` or `without (…)` is used.
	pub action: AggregationAction,
	pub labels: Vec<String>,
}

/// AST node.
#[derive(Debug, PartialEq)]
pub enum Node {
	/// Operator: `a + ignoring (foo) b`
	Operator {
		/// First operand.
		x: Box<Node>,
		/// Operator itself.
		op: Op,
		/// Second operand.
		y: Box<Node>
	},
	/// Time series vector.
	Vector(Vector),
	/// Floating point number.
	Scalar(f32),
	/// String literal.
	String(String),
	/// Function call or aggregation operator.
	Function {
		// Function name.
		name: String,
		// Function arguments.
		args: Vec<Node>,
		// Aggregation operator modifiers (`by(…)`/`without(…)`).
		aggregation: Option<AggregationMod>,
	},
	/// Unary negation, e.g. `-b` in `a + -b`
	Negation(Box<Node>),
}
impl Node {
	// these functions are here primarily to avoid explicit mention of `Box::new()` in the code

	fn operator(x: Node, op: Op, y: Node) -> Node {
		Node::Operator {
			x: Box::new(x),
			op,
			y: Box::new(y)
		}
	}
	fn negation(x: Node) -> Node {
		Node::Negation(Box::new(x))
	}
}

named!(label_list <CompleteByteSlice, Vec<String>>, ws!(delimited!(
	char!('('),
	separated_list!(char!(','), label_name),
	char!(')')
)));

named!(function_aggregation <CompleteByteSlice, AggregationMod>, ws!(do_parse!(
	action: alt!(
		  tag!("by") => { |_| AggregationAction::By }
		| tag!("without") => { |_| AggregationAction::Without }
	) >>
	labels: label_list >>
	(AggregationMod { action, labels })
)));

// it's up to the library user to decide whether argument list is valid or not
fn function_args(input: CompleteByteSlice, allow_periods: bool) -> IResult<CompleteByteSlice, Vec<Node>> {
	ws!(
		input,
		delimited!(
			char!('('),
			separated_list!(char!(','), alt!(
				  call!(expression, allow_periods) => { |e| e }
				| string => { |s| Node::String(s) }
			)),
			char!(')')
		)
	)
}

fn function(input: CompleteByteSlice, allow_periods: bool) -> IResult<CompleteByteSlice, Node> {
	ws!(
		input,
		do_parse!(
			// I have no idea what counts as a function name but label_name fits well for what's built into the prometheus so let's use that
			name: label_name >>
			args_agg: alt!(
				// both 'sum by (label, label) (foo)' and 'sum(foo) by (label, label)' are valid
				do_parse!(
					args: call!(function_args, allow_periods) >>
					aggregation: opt!(function_aggregation) >>
					((args, aggregation))
				)
				|
				do_parse!(
					aggregation: opt!(function_aggregation) >>
					args: call!(function_args, allow_periods) >>
					((args, aggregation))
				)
			) >>
			({
				let (args, aggregation) = args_agg;
				Node::Function { name, args, aggregation }
			})
		)
	)
}

fn atom(input: CompleteByteSlice, allow_periods: bool) -> IResult<CompleteByteSlice, Node> {
	ws!(
		input,
		alt!(
			map!(tag_no_case!("NaN"), |_| Node::Scalar(::std::f32::NAN)) // XXX define Node::NaN instead?
			|
			map!(
				flat_map!(call!(recognize_float), parse_to!(f32)),
				Node::Scalar
			)
			|
			// unary + does nothing
			preceded!(char!('+'), call!(atom, allow_periods))
			|
			// unary -, well, negates whatever is following it
			map!(preceded!(char!('-'), call!(atom, allow_periods)), |a| Node::negation(a))
			|
			// function call is parsed before vector: the latter can actually consume function name as a vector, effectively rendering the rest of the expression invalid
			call!(function, allow_periods)
			|
			// FIXME? things like 'and' and 'group_left' are not supposed to parse as a vector: prometheus lexes them unambiguously
			map!(call!(vector, allow_periods), Node::Vector)
			|
			delimited!(char!('('), call!(expression, allow_periods), char!(')'))
		)
	)
}

macro_rules! with_modifier {
	// this macro mimicks another parser macros, hence implicit input argument, $i
	// for comparison, see nom's call!()
	($i:expr, $literal:expr, $op:expr) => (
		map!(
			$i,
			preceded!(tag!($literal), opt!(op_modifier)),
			|op_mod| $op(op_mod)
		)
	)
}

macro_rules! with_bool_modifier {
	($i:expr, $literal:expr, $op:expr) => (
		ws!($i, do_parse!(
			tag!($literal) >>
			boolness: opt!(tag!("bool")) >>
			op_mod: opt!(op_modifier) >>
			($op(boolness.is_some(), op_mod))
		))
	)
}

named!(op_modifier <CompleteByteSlice, OpMod>, ws!(do_parse!(
	action: alt!(
		  tag!("on") => { |_| OpModAction::RestrictTo }
		| tag!("ignoring") => { |_| OpModAction::Ignore }
	) >>
	labels: label_list >>
	// TODO > Grouping modifiers can only be used for comparison and arithmetic. Operations as and, unless and or operations match with all possible entries in the right vector by default.
	group: opt!(ws!(do_parse!(
		side: alt!(
			  tag!("group_left") => { |_| OpGroupSide::Left }
			| tag!("group_right") => { |_| OpGroupSide::Right }
		) >>
		labels: map!(
			opt!(label_list),
			|labels| labels.unwrap_or(vec![])
		) >>
		(OpGroupMod { side, labels })
	))) >>
	(OpMod { action, labels, group })
)));

// ^ is right-associative, so we can actually keep it simple and recursive
fn power(input: CompleteByteSlice, allow_periods: bool) -> IResult<CompleteByteSlice, Node> {
	ws!(
		input,
		do_parse!(
			x: call!(atom, allow_periods) >>
			y: opt!(tuple!(
				with_modifier!("^", Op::Pow),
				call!(power, allow_periods)
			)) >>
			( match y {
				None => x,
				Some((op, y)) => Node::operator(x, op, y),
			} )
		)
	)
}

// foo op bar op baz → Node[Node[foo op bar] op baz]
macro_rules! left_op {
	// $next is the parser for operator that takes precenence, or any other kind of non-operator token sequence
	($name:ident, $next:ident, $op:ident!($($op_args:tt)*)) => (
		fn $name(input: CompleteByteSlice, allow_periods: bool) -> IResult<CompleteByteSlice, Node>{
			ws!(
				input,
				do_parse!(
					x: call!($next, allow_periods) >>
					ops: many0!(tuple!(
						$op!($($op_args)*),
						call!($next, allow_periods)
					)) >>
					({
						let mut x = x;
						for (op, y) in ops {
							x = Node::operator(x, op, y);
						}
						x
					})
				)
			)
		}
	);
}

left_op!(mul_div_mod, power, alt!(
	  with_modifier!("*", Op::Mul)
	| with_modifier!("/", Op::Div)
	| with_modifier!("%", Op::Mod)
));

left_op!(plus_minus, mul_div_mod, alt!(
	  with_modifier!("+", Op::Plus)
	| with_modifier!("-", Op::Minus)
));

// if you thing this kind of operator chaining makes little to no sense, think again: it actually matches 'foo' that is both '> bar' and '!= baz'.
// or, speaking another way: comparison operators are really just filters for values in a vector, and this is a chain of filters.
left_op!(comparison, plus_minus, alt!(
	  with_bool_modifier!("==", Op::Eq)
	| with_bool_modifier!("!=", Op::Ne)
	| with_bool_modifier!("<=", Op::Le)
	| with_bool_modifier!(">=", Op::Ge)
	| with_bool_modifier!("<",  Op::Lt)
	| with_bool_modifier!(">",  Op::Gt)
));

left_op!(and_unless, comparison, alt!(
	  with_modifier!("and", Op::And)
	| with_modifier!("unless", Op::Unless)
));

left_op!(or_op, and_unless, with_modifier!("or", Op::Or));

pub(crate) fn expression(input: CompleteByteSlice, allow_periods: bool) -> IResult<CompleteByteSlice, Node> {
	call!(input, or_op, allow_periods)
}

#[allow(unused_imports)]
#[cfg(test)]
mod tests {
	use super::*;
	use vec;
	use nom::ErrorKind;

	use self::Node::{Scalar, Function};
	use self::Op::*;

	// cannot 'use self::Node::operator' for some reason
	#[allow(non_upper_case_globals)]
	const operator: fn(Node, Op, Node) -> Node = Node::operator;
	#[allow(non_upper_case_globals)]
	const negation: fn(Node) -> Node = Node::negation;

	// vector parsing is already tested in `mod vec`, so use that parser instead of crafting lengthy structs all over the test functions
	fn vector(expr: &str) -> Node {
		match vec::vector(cbs(expr), false) {
			Ok((CompleteByteSlice(b""), x)) => Node::Vector(x),
			_ => panic!("failed to parse label correctly")
		}
	}

	fn cbs(s: &str) -> CompleteByteSlice {
		CompleteByteSlice(s.as_bytes())
	}

	#[test]
	fn scalar() {
		scalar_single("123",       123.);
		scalar_single("-123",     -123.);

		scalar_single("123.",      123.);
		scalar_single("-123.",    -123.);

		scalar_single("123.45",    123.45);
		scalar_single("-123.45",  -123.45);

		scalar_single(".123",      0.123);
		scalar_single("-.123",    -0.123);

		scalar_single("123e5",     123e5);
		scalar_single("-123e5",   -123e5);

		scalar_single("1.23e5",    1.23e5);
		scalar_single("-1.23e5",  -1.23e5);

		scalar_single("1.23e-5",   1.23e-5);
		scalar_single("-1.23e-5", -1.23e-5);
	}

	fn scalar_single(input: &str, output: f32) {
		assert_eq!(expression(cbs(input), false), Ok((cbs(""), Scalar(output))));
	}

	#[test]
	fn ops() {
		assert_eq!(
			expression(cbs("foo > bar != 0 and 15.5 < xyzzy"), false),
			Ok((cbs(""), operator(
				operator(
					operator(vector("foo"), Gt(false, None), vector("bar")),
					Ne(false, None),
					Scalar(0.)
				),
				And(None),
				operator(Scalar(15.5), Lt(false, None), vector("xyzzy")),
			)))
		);

		assert_eq!(
			expression(cbs("foo + bar - baz <= quux + xyzzy"), false),
			Ok((cbs(""), operator(
				operator(
					operator(vector("foo"), Plus(None), vector("bar")),
					Minus(None),
					vector("baz"),
				),
				Le(false, None),
				operator(vector("quux"), Plus(None), vector("xyzzy")),
			)))
		);

		assert_eq!(
			expression(cbs("foo + bar % baz"), false),
			Ok((cbs(""), operator(
				vector("foo"),
				Plus(None),
				operator(vector("bar"), Mod(None), vector("baz")),
			)))
		);

		assert_eq!(
			expression(cbs("x^y^z"), false),
			Ok((cbs(""), operator(
				vector("x"),
				Pow(None),
				operator(vector("y"), Pow(None), vector("z")),
			)))
		);

		assert_eq!(
			expression(cbs("(a+b)*c"), false),
			Ok((cbs(""), operator(
				operator(vector("a"), Plus(None), vector("b")),
				Mul(None),
				vector("c"),
			)))
		);
	}

	#[test]
	fn op_mods() {
		assert_eq!(
			expression(cbs("foo + ignoring (instance) bar / on (cluster) baz"), false),
			Ok((cbs(""), operator(
				vector("foo"),
				Plus(Some(OpMod {
					action: OpModAction::Ignore,
					labels: vec!["instance".to_string()],
					group: None,
				})),
				operator(
					vector("bar"),
					Div(Some(OpMod {
						action: OpModAction::RestrictTo,
						labels: vec!["cluster".to_string()],
						group: None,
					})),
					vector("baz"),
				)
			)))
		);

		assert_eq!(
			expression(cbs("foo + ignoring (instance) group_right bar / on (cluster, shmuster) group_left (job) baz"), false),
			Ok((cbs(""), operator(
				vector("foo"),
				Plus(Some(OpMod {
					action: OpModAction::Ignore,
					labels: vec!["instance".to_string()],
					group: Some(OpGroupMod { side: OpGroupSide::Right, labels: vec![] }),
				})),
				operator(
					vector("bar"),
					Div(Some(OpMod {
						action: OpModAction::RestrictTo,
						labels: vec!["cluster".to_string(), "shmuster".to_string()],
						group: Some(OpGroupMod { side: OpGroupSide::Left, labels: vec!["job".to_string()] }),
					})),
					vector("baz"),
				)
			)))
		);

		assert_eq!(
			expression(cbs("node_cpu{cpu='cpu0'} > bool ignoring (cpu) node_cpu{cpu='cpu1'}"), false),
			Ok((cbs(""), operator(
				vector("node_cpu{cpu='cpu0'}"),
				Gt(true, Some(OpMod {
					action: OpModAction::Ignore,
					labels: vec!["cpu".to_string()],
					group: None,
				})),
				vector("node_cpu{cpu='cpu1'}"),
			)))
		);
	}

	#[test]
	fn unary() {
		assert_eq!(
			expression(cbs("a + -b"), false),
			Ok((cbs(""), operator(
				vector("a"),
				Plus(None),
				negation(vector("b")),
			)))
		);

		assert_eq!(
			expression(cbs("a ^ - 1 - b"), false),
			Ok((cbs(""), operator(
				operator(
					vector("a"),
					Pow(None),
					negation(Scalar(1.)),
				),
				Minus(None),
				vector("b"),
			)))
		);

		assert_eq!(
			expression(cbs("a ^ - (1 - b)"), false),
			Ok((cbs(""), operator(
				vector("a"),
				Pow(None),
				negation(operator(
					Scalar(1.),
					Minus(None),
					vector("b"),
				)),
			)))
		);

		// yes, these are also valid

		assert_eq!(
			expression(cbs("a +++++++ b"), false),
			Ok((cbs(""), operator(
				vector("a"),
				Plus(None),
				vector("b"),
			)))
		);

		assert_eq!(
			expression(cbs("a * --+-b"), false),
			Ok((cbs(""), operator(
				vector("a"),
				Mul(None),
				negation(negation(negation(vector("b")))),
			)))
		);
	}

	#[test]
	fn functions() {
		assert_eq!(
			expression(cbs("foo() + bar(baz) + quux(xyzzy, plough)"), false),
			Ok((cbs(""), operator(
				operator(
					Function {
						name: "foo".to_string(),
						args: vec![],
						aggregation: None,
					},
					Plus(None),
					Function {
						name: "bar".to_string(),
						args: vec![vector("baz")],
						aggregation: None,
					},
				),
				Plus(None),
				Function {
					name: "quux".to_string(),
					args: vec![
						vector("xyzzy"),
						vector("plough"),
					],
					aggregation: None,
				},
			)))
		);

		assert_eq!(
			expression(cbs("round(rate(whatever [5m]) > 0, 0.2)"), false),
			Ok((cbs(""),
				Function {
					name: "round".to_string(),
					args: vec![
						operator(
							Function {
								name: "rate".to_string(),
								args: vec![vector("whatever [5m]")],
								aggregation: None,
							},
							Gt(false, None),
							Scalar(0.),
						),
						Scalar(0.2)
					],
					aggregation: None,
				}
			))
		);

		assert_eq!(
			expression(cbs("label_replace(up, 'instance', '', 'instance', '.*')"), false),
			Ok((cbs(""), Function {
				name: "label_replace".to_string(),
				args: vec![
					vector("up"),
					Node::String("instance".to_string()),
					Node::String("".to_string()),
					Node::String("instance".to_string()),
					Node::String(".*".to_string()),
				],
				aggregation: None,
			}))
		);
	}

	#[test]
	fn agg_functions() {
		assert_eq!(
			expression(cbs("sum(foo) by (bar) * count(foo) without (bar)"), false),
			Ok((cbs(""), operator(
				Function {
					name: "sum".to_string(),
					args: vec![vector("foo")],
					aggregation: Some(AggregationMod {
						action: AggregationAction::By,
						labels: vec!["bar".to_string()]
					}),
				},
				Mul(None),
				Function {
					name: "count".to_string(),
					args: vec![vector("foo")],
					aggregation: Some(AggregationMod {
						action: AggregationAction::Without,
						labels: vec!["bar".to_string()]
					}),
				},
			)))
		);

		assert_eq!(
			expression(cbs("sum by (bar) (foo) * count without (bar) (foo)"), false),
			Ok((cbs(""), operator(
				Function {
					name: "sum".to_string(),
					args: vec![vector("foo")],
					aggregation: Some(AggregationMod {
						action: AggregationAction::By,
						labels: vec!["bar".to_string()]
					}),
				},
				Mul(None),
				Function {
					name: "count".to_string(),
					args: vec![vector("foo")],
					aggregation: Some(AggregationMod {
						action: AggregationAction::Without,
						labels: vec!["bar".to_string()]
					}),
				},
			)))
		);
	}
}