-
Notifications
You must be signed in to change notification settings - Fork 74
/
lang.rs
3273 lines (3078 loc) · 108 KB
/
lang.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
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::fmt::Debug;
use std::ops::Range;
use std::str;
use itertools::Itertools;
use lazy_static::lazy_static;
use nom::bytes::complete::escaped;
use nom::combinator::not;
use nom::multi::{fold_many0, fold_many1};
use nom::sequence::{delimited, separated_pair};
use nom::{
branch::alt,
bytes::complete::{take, take_while, take_while1},
character::complete::{anychar, digit1, multispace0, multispace1, none_of, satisfy},
character::{is_alphabetic, is_alphanumeric},
combinator::{eof, map, map_res, opt, peek, recognize},
error::ParseError,
multi::{many0, many_till, separated_list0, separated_list1},
number::complete::double,
sequence::{pair, tuple},
IResult, InputIter, Parser, Slice,
};
use nom_locate::position;
use nom_locate::LocatedSpan;
use nom_supreme::error::ErrorTree;
use nom_supreme::parser_ext::ParserExt;
use nom_supreme::tag::complete::tag;
use crate::alias::{self, AliasPipeline};
use crate::data;
use crate::errors::{ErrorBuilder, QueryContainer};
use crate::pipeline::CompileError;
pub const VALID_AGGREGATES: &[&str] = &[
"count",
"min",
"average",
"avg",
"max",
"sum",
"count_distinct",
"sort",
];
pub const VALID_INLINE: &[&str] = &[
"parse",
"limit",
"json",
"logfmt",
"total",
"fields",
"where",
"split",
"timeslice",
];
lazy_static! {
pub static ref VALID_OPERATORS: Vec<&'static str> = {
[
VALID_INLINE,
VALID_AGGREGATES,
alias::LOADED_KEYWORDS.as_slice(),
]
.concat()
};
}
pub const RESERVED_FILTER_WORDS: &[&str] = &["AND", "OR", "NOT"];
#[derive(Debug)]
struct Error(Range<usize>, String);
/// Type used to track the current fragment being parsed and its location in the original input.
pub type Span<'a> = LocatedSpan<&'a str, &'a QueryContainer>;
pub type LResult<I, O, E = ErrorTree<I>> = Result<(I, O), nom::Err<E>>;
pub type QueryRange = Range<usize>;
/// Container for values from the query that records the location in the query string.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Positioned<T> {
pub range: QueryRange,
pub value: T,
}
impl<T> Positioned<T> {
pub fn into(&self) -> &T {
&self.value
}
}
/// Methods for converting a Span to different ranges over the span
trait ToRange {
/// Return the entire Span as a Range
fn to_range(&self) -> Range<usize>;
/// Return a range from the current offset in the Span to the "sync point". For the
/// angle-grinder syntax, the sync points are the vertical bar, end-of-query, and closing
/// braces/parens/etc...
fn to_sync_point(&self) -> Range<usize>;
/// Return a range from the current offset in the Span to the next whitespace
fn to_whitespace(&self) -> Range<usize>;
}
impl<'a> ToRange for Span<'a> {
fn to_range(&self) -> Range<usize> {
let start = self.location_offset();
let end = start + self.fragment().len();
start..end
}
fn to_sync_point(&self) -> Range<usize> {
let s: &str = self.fragment();
let sync = s
.chars()
.find_position(|ch| matches!(ch, '|' | ')' | ']' | '}'));
let end = sync.map(|pair| pair.0).unwrap_or(s.len());
Range {
start: self.location_offset(),
end: self.location_offset() + end,
}
}
fn to_whitespace(&self) -> Range<usize> {
let s: &str = self.fragment();
let sync = s
.chars()
.find_position(|ch| matches!(ch, ' ' | '\t' | '\n'));
let end = sync.map(|pair| pair.0).unwrap_or(s.len());
Range {
start: self.location_offset(),
end: self.location_offset() + end,
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ComparisonOp {
Eq,
Neq,
Gt,
Lt,
Gte,
Lte,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ArithmeticOp {
Add,
Subtract,
Multiply,
Divide,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum LogicalOp {
And,
Or,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum BinaryOp {
Comparison(ComparisonOp),
Arithmetic(ArithmeticOp),
Logical(LogicalOp),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum UnaryOp {
Not,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DataAccessAtom {
Key(String),
Index(i64),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Expr {
Column {
head: DataAccessAtom,
rest: Vec<DataAccessAtom>,
},
Unary {
op: UnaryOp,
operand: Box<Expr>,
},
Binary {
op: BinaryOp,
left: Box<Expr>,
right: Box<Expr>,
},
FunctionCall {
name: String,
args: Vec<Expr>,
},
IfOp {
cond: Box<Expr>,
value_if_true: Box<Expr>,
value_if_false: Box<Expr>,
},
Value(data::Value),
Error,
}
impl Expr {
pub fn column(key: &str) -> Expr {
Expr::Column {
head: DataAccessAtom::Key(key.to_owned()),
rest: vec![],
}
}
}
/// Debug helper
pub fn dbg_dmp<'a, F, O, E>(
mut f: F,
context: &'static str,
) -> impl FnMut(Span<'a>) -> IResult<Span<'a>, O, E>
where
F: FnMut(Span<'a>) -> IResult<Span<'a>, O, E>,
{
move |i: Span<'a>| match f(i) {
Err(e) => {
println!("{}: Error at:\n{}", context, i);
Err(e)
}
Ok((s, a)) => {
println!("{}: Ok at:\n{}\nnext:\n{}", context, i, s.fragment());
Ok((s, a))
}
}
}
/// Combinator that expects the given parser to succeed. If the parser returns an error:
/// - the given error message is logged
/// - the input is consumed up to the sync point
/// - None is returned
fn expect<'a, F, E, T>(
mut parser: F,
error_msg: E,
) -> impl FnMut(Span<'a>) -> IResult<Span, Option<T>>
where
F: FnMut(Span<'a>) -> IResult<Span, T>,
E: ToString,
{
move |input: Span<'a>| match parser(input) {
Ok((remaining, out)) => Ok((remaining, Some(out))),
Err(nom::Err::Error(nom::error::Error { input, .. }))
| Err(nom::Err::Failure(nom::error::Error { input, .. })) => {
let r = input.to_sync_point();
let end = r.end - input.location_offset();
input
.extra
.report_error_for(error_msg.to_string())
.with_code_range(r, "")
.send_report();
Ok((input.slice(end..), None))
}
Err(err) => Err(err),
}
}
/// Combinator that expects the given parser to succeed. If the parser returns an error:
/// - the given error function is called with the range
/// - the input is consumed up to the sync point
/// - None is returned
fn expect_fn<'a, F, O, EF>(
mut parser: F,
mut error_fn: EF,
) -> impl FnMut(Span<'a>) -> IResult<Span, Option<O>>
where
F: Parser<Span<'a>, O, nom::error::Error<Span<'a>>>,
EF: FnMut(&QueryContainer, QueryRange),
{
move |input: Span<'a>| match parser.parse(input) {
Ok((remaining, out)) => Ok((remaining, Some(out))),
Err(nom::Err::Error(nom::error::Error { input, .. }))
| Err(nom::Err::Failure(nom::error::Error { input, .. })) => {
let r = input.to_sync_point();
let end = r.end - input.location_offset();
error_fn(input.extra, r);
let next = input.slice(end..);
Ok((next, None))
}
Err(err) => Err(err),
}
}
/// A version of the `delimited()` combinator() that calls an error-handling function when the
/// terminator parser fails.
pub fn expect_delimited<'a, O1, O2, O3, F, G, H, EF>(
mut first: F,
mut second: G,
mut third: H,
mut error_fn: EF,
) -> impl FnMut(Span<'a>) -> IResult<Span<'a>, O2, nom::error::Error<Span<'a>>>
where
F: Parser<Span<'a>, O1, nom::error::Error<Span<'a>>>,
G: Parser<Span<'a>, O2, nom::error::Error<Span<'a>>>,
H: Parser<Span<'a>, O3, nom::error::Error<Span<'a>>>,
EF: FnMut(&QueryContainer, QueryRange),
{
move |input: Span<'a>| {
let full_r = input.to_sync_point();
let (input, _) = first.parse(input)?;
let (input, o2) = second.parse(input)?;
match third.parse(input) {
Ok((input, _)) => Ok((input, o2)),
Err(_) => {
let start = input.location_offset();
let mut remaining = input;
loop {
if remaining.is_empty() {
error_fn(
remaining.extra,
Range {
start: full_r.start,
end: remaining.location_offset(),
},
);
return Ok((remaining, o2));
}
remaining = remaining.slice(1..);
let end = remaining.location_offset();
let res = third.parse(remaining);
if let Ok((remaining, _)) = res {
remaining
.extra
.report_error_for("unhandled input")
.with_code_range(Range { start, end }, "")
.send_report();
return Ok((remaining, o2));
}
}
}
}
}
}
/// Combinator that expects some optional whitespace followed by the vertical bar or EOF. If that
/// input is not found, the error message is logged.
fn expect_pipe<'a, M>(
error_msg: M,
) -> impl FnMut(Span<'a>) -> IResult<Span, Option<(Span<'a>, Span<'a>)>>
where
M: ToString,
{
expect(peek(multispace0.and(tag("|").or(eof))), error_msg)
}
/// The KeywordType determines how a keyword string should be interpreted.
#[derive(Debug, PartialEq, Eq, Clone)]
enum KeywordType {
/// The keyword string should exactly match the input.
Exact,
/// The keyword string can contain wildcards.
Wildcard,
Regex,
}
/// Represents a `keyword` search string.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Keyword(String, KeywordType);
impl Keyword {
/// Create a Keyword that will exactly match an input string.
pub fn new_exact(str: String) -> Keyword {
Keyword(str, KeywordType::Exact)
}
/// Create a Keyword that can contain wildcards
pub fn new_wildcard(str: String) -> Keyword {
Keyword(str, KeywordType::Wildcard)
}
/// Create a Keyword that can contain wildcards
pub fn new_regex(str: String) -> Keyword {
Keyword(str, KeywordType::Regex)
}
/// Test if this is an empty keyword string
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Convert this keyword to a `regex::Regex` object.
pub fn to_regex(&self) -> regex::Regex {
if self.1 == KeywordType::Regex {
return regex::Regex::new(&self.0).unwrap();
}
let mut regex_str = regex::escape(&self.0.replace("\\\"", "\"")).replace(' ', "\\s");
regex_str.insert_str(0, "(?i)");
if self.1 == KeywordType::Wildcard {
regex_str = regex_str.replace("\\*", "(.*?)");
// If it ends with a star, we need to ensure we read until the end.
if self.0.ends_with('*') {
regex_str.push('$');
}
}
regex::Regex::new(®ex_str).unwrap()
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Search {
And(Vec<Search>),
Or(Vec<Search>),
Not(Box<Search>),
Keyword(Keyword),
}
impl Search {
pub fn from_quoted_input(s: String) -> Option<Self> {
if s.is_empty() {
None
} else {
Some(Search::Keyword(Keyword::new_exact(s)))
}
}
pub fn from_keyword_input(s: &str) -> Option<Self> {
let trimmed = s.trim_matches('*');
if trimmed.is_empty() {
None
} else {
Some(Search::Keyword(Keyword::new_wildcard(trimmed.to_string())))
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Operator {
RenderedAlias(Vec<Operator>),
Inline(Positioned<InlineOperator>),
MultiAggregate(MultiAggregateOperator),
Sort(SortOperator),
Error,
}
#[derive(Debug, PartialEq, Clone)]
pub enum InlineOperator {
Json {
input_column: Option<Expr>,
},
Logfmt {
input_column: Option<Expr>,
},
Parse {
pattern: Keyword,
fields: Vec<String>,
input_column: (Option<Positioned<Expr>>, Option<Positioned<Expr>>),
no_drop: bool,
},
Fields {
mode: FieldMode,
fields: Vec<String>,
},
Where {
expr: Option<Positioned<Expr>>,
},
Limit {
/// The count for the limit is pretty loosely typed at this point, the next phase will
/// check the value to see if it's sane or provide a default if no number was given.
count: Option<Positioned<f64>>,
},
Split {
separator: String,
input_column: Option<Expr>,
output_column: Option<Expr>,
},
Timeslice {
input_column: Expr,
duration: Option<chrono::Duration>,
output_column: Option<String>,
},
Total {
input_column: Expr,
output_column: String,
},
FieldExpression {
value: Expr,
name: String,
},
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum FieldMode {
Only,
Except,
}
#[derive(Debug, PartialEq, Clone, Eq)]
pub enum SortMode {
Ascending,
Descending,
}
#[derive(Debug, PartialEq, Clone)]
pub enum AggregateFunction {
Count {
condition: Option<Expr>,
},
Sum {
column: Expr,
},
Min {
column: Expr,
},
Average {
column: Expr,
},
Max {
column: Expr,
},
Percentile {
percentile: f64,
percentile_str: String,
column: Expr,
},
CountDistinct {
column: Option<Positioned<Vec<Expr>>>,
},
Error,
}
impl AggregateFunction {
fn default_name(&self) -> String {
match self {
AggregateFunction::Count { .. } => "_count".to_string(),
AggregateFunction::Sum { .. } => "_sum".to_string(),
AggregateFunction::Min { .. } => "_min".to_string(),
AggregateFunction::Average { .. } => "_average".to_string(),
AggregateFunction::Max { .. } => "_max".to_string(),
AggregateFunction::Percentile {
ref percentile_str, ..
} => format!("p{}", percentile_str),
AggregateFunction::CountDistinct { .. } => "_countDistinct".to_string(),
AggregateFunction::Error => "_err".to_string(),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct MultiAggregateOperator {
pub key_cols: Vec<Expr>,
pub key_col_headers: Vec<String>,
pub aggregate_functions: Vec<(String, Positioned<AggregateFunction>)>,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct SortOperator {
pub sort_cols: Vec<Expr>,
pub direction: SortMode,
}
#[derive(Debug, PartialEq, Clone)]
pub struct Query {
pub search: Search,
pub operators: Vec<Operator>,
}
/// Parses the +/- binary operators
fn addsub_op(input: Span) -> IResult<Span, ArithmeticOp> {
alt((
tag("+").map(|_| ArithmeticOp::Add),
tag("-").map(|_| ArithmeticOp::Subtract),
))(input)
}
/// Parses an argument list for a function
fn arg_list(input: Span) -> IResult<Span, Vec<Expr>> {
expect_delimited(
tag("(").and(multispace0),
separated_list0(tag(","), delimited(multispace0, opt_expr, multispace0)),
tag(")"),
|qc, r| {
qc.report_error_for("unterminated function call")
.with_code_range(r, "unterminated function call")
.with_resolution("Insert a right parenthesis to terminate this call")
.send_report()
},
)
.parse(input)
}
/// Parses a, potentially optional, argument list for a function that has a single parameter
fn single_arg(description: &'static str) -> impl Clone + Fn(Span) -> IResult<Span, Expr> {
move |input: Span| {
expect_delimited(
tag("(").and(multispace0),
expect_fn(opt_expr, |qc, r| {
qc.report_error_for("this operator takes 1 argument, but 0 were supplied")
.with_code_range(r, "- supplied 0 arguments")
.with_resolution(format!("the argument should supply {}", description))
.send_report();
})
.map(|e| e.unwrap_or(Expr::Error)),
tag(")"),
|qc, r| {
qc.report_error_for("unterminated function call")
.with_code_range(r, "unterminated function call")
.with_resolution("Insert a right parenthesis to terminate this call")
.send_report()
},
)
.parse(input)
}
}
/// A version of the single_arg parser that logs an error if no argument list was provided
fn req_single_arg(description: &'static str) -> impl Clone + Fn(Span) -> IResult<Span, Expr> {
move |input: Span| {
expect_fn(single_arg(description), |qc, r| {
qc.report_error_for(format!(
"expecting a parenthesized argument that supplies {}",
description
))
.with_code_range(r, "")
.send_report()
})
.map(|e| e.unwrap_or(Expr::Error))
.parse(input)
}
}
/// Combinator that checks for an optional keyword that should be followed by an expression
fn kw_expr(
keyword: &'static str,
description: &'static str,
) -> impl Fn(Span) -> IResult<Span, Option<Expr>> {
move |input: Span| {
let res = opt(tag(keyword).preceded_by(multispace1)).parse(input)?;
match res {
(input, None) => Ok((input, None)),
(input, Some(keyword_span)) => {
expect_fn(opt_expr.preceded_by(multispace1), |qc, _r| {
qc.report_error_for(format!(
"expecting an expression that supplies {}",
description
))
.with_code_range(
keyword_span.to_range(),
"should be followed by an expression",
)
.send_report();
})
.map(|e| e.map(Some).unwrap_or(Some(Expr::Error)))
.parse(input)
}
}
}
}
fn fcall(input: Span) -> IResult<Span, Expr> {
ident
.and(arg_list)
.map(|(name, args)| Expr::FunctionCall { name, args })
.parse(input)
}
fn if_op(input: Span) -> IResult<Span, Expr> {
tag("if")
.precedes(with_pos(arg_list))
.map(|Positioned { range, value: args }| match args.as_slice() {
[cond, value_if_true, value_if_false] => Expr::IfOp {
cond: Box::new(cond.clone()),
value_if_true: Box::new(value_if_true.clone()),
value_if_false: Box::new(value_if_false.clone()),
},
_ => {
input
.extra
.report_error_for(
"the 'if' operator expects exactly 3 arguments, the condition, \
value-if-true, and value-if-false",
)
.with_code_range(range, format!("supplied {} arguments", args.len()))
.send_report();
Expr::Error
}
})
.parse(input)
}
fn filter_atom(input: Span) -> IResult<Span, Option<Search>> {
let keyword = take_while1(is_keyword).map(|i: Span| Search::from_keyword_input(i.fragment()));
alt((quoted_string.map(Search::from_quoted_input), keyword))(input)
}
fn filter_not(input: Span) -> IResult<Span, Option<Search>> {
tag("NOT")
.precedes(multispace1)
.precedes(low_filter)
.map(|optk| optk.map(|k| Search::Not(Box::new(k))))
.parse(input)
}
fn sourced_expr(input: Span) -> IResult<Span, (String, Expr)> {
recognize(expr)
.map(|ex| (ex.fragment().trim().to_string(), expr(ex).ok().unwrap().1))
.parse(input)
}
fn sourced_expr_list(input: Span) -> IResult<Span, Vec<(String, Expr)>> {
separated_list1(tag(",").delimited_by(multispace0), sourced_expr)(input)
}
fn sort_mode(input: Span) -> IResult<Span, SortMode> {
alt((
alt((tag("asc"), tag("ascending"))).map(|_| SortMode::Ascending),
alt((tag("desc"), tag("dsc"), tag("descending"))).map(|_| SortMode::Descending),
))(input)
}
fn sort(input: Span) -> IResult<Span, Operator> {
tuple((
tag("sort").precedes(
opt(tag("by")
.delimited_by(multispace1)
.precedes(sourced_expr_list))
.map(|opt_cols| opt_cols.unwrap_or_default()),
),
opt(sort_mode.preceded_by(multispace1))
.map(|opt_mode| opt_mode.unwrap_or(SortMode::Ascending)),
))
.map(|(mut sort_cols, direction)| {
Operator::Sort(SortOperator {
sort_cols: sort_cols.drain(..).map(|(_name, ex)| ex).collect(),
direction,
})
})
.parse(input)
}
fn filter_explicit_and(input: Span) -> IResult<Span, Option<Search>> {
separated_pair(low_filter, tag("AND").delimited_by(multispace1), low_filter)
.map(|p| match p {
(Some(l), Some(r)) => Some(Search::And(vec![l, r])),
(Some(l), None) => Some(l),
(None, Some(r)) => Some(r),
(None, None) => None,
})
.parse(input)
}
fn filter_explicit_or(input: Span) -> IResult<Span, Option<Search>> {
separated_pair(mid_filter, tag("OR").delimited_by(multispace1), mid_filter)
.map(|p| match p {
(Some(l), Some(r)) => Some(Search::Or(vec![l, r])),
(Some(l), None) => Some(l),
(None, Some(r)) => Some(r),
(None, None) => None,
})
.parse(input)
}
fn low_filter(input: Span) -> IResult<Span, Option<Search>> {
alt((
filter_not,
filter_atom,
expect_delimited(tag("("), high_filter, tag(")"), |qc, r| {
qc.report_error_for("unterminated parenthesized filter")
.with_code_range(r, "unterminated parenthesized filter")
.with_resolution("Insert a right parenthesis to terminate this filter")
.send_report()
}),
))(input)
}
fn mid_filter(input: Span) -> IResult<Span, Option<Search>> {
alt((filter_explicit_and, low_filter))(input)
}
fn high_filter(input: Span) -> IResult<Span, Option<Search>> {
alt((filter_explicit_or, mid_filter))(input)
}
fn end_of_query(input: Span) -> IResult<Span, Span> {
peek(multispace0.precedes(alt((peek(tag("|")), eof))))(input)
}
fn parse_search(input: Span) -> IResult<Span, Search> {
many_till(high_filter.delimited_by(multispace0), end_of_query)
.map(|(s, _)| Search::And(s.into_iter().flatten().collect()))
.parse(input)
}
fn is_ident(c: char) -> bool {
is_alphanumeric(c as u8) || c == '_'
}
fn starts_ident(c: char) -> bool {
is_alphabetic(c as u8) || c == '_'
}
/// Tests if the input character can be part of a search keyword.
///
/// Based on the SumoLogic keyword syntax:
///
/// https://help.sumologic.com/05Search/Get-Started-with-Search/How-to-Build-a-Search/Keyword-Search-Expressions
fn is_keyword(c: char) -> bool {
match c {
'-' | '_' | ':' | '/' | '.' | '+' | '@' | '#' | '$' | '%' | '^' | '*' => true,
alpha if is_alphanumeric(alpha as u8) => true,
_ => false,
}
}
/// Parses a single number with a time suffix
fn duration_fragment(input: Span) -> IResult<Span, chrono::Duration> {
let (input, amount) = i64_parse(input)?;
alt((
tag("ns").map(move |_| chrono::Duration::nanoseconds(amount)),
tag("us").map(move |_| chrono::Duration::microseconds(amount)),
tag("ms").map(move |_| chrono::Duration::milliseconds(amount)),
tag("s").map(move |_| chrono::Duration::seconds(amount)),
tag("m").map(move |_| chrono::Duration::minutes(amount)),
tag("h").map(move |_| chrono::Duration::hours(amount)),
tag("d").map(move |_| chrono::Duration::days(amount)),
tag("w").map(move |_| chrono::Duration::weeks(amount)),
))
.parse(input)
}
/// Parses a duration that can be made up of multiple integer/time-suffix values
fn duration(input: Span) -> IResult<Span, chrono::Duration> {
fold_many1(duration_fragment, chrono::Duration::zero, |left, right| {
left + right
})(input)
}
fn dot_property(input: Span) -> IResult<Span, DataAccessAtom> {
tag(".")
.precedes(ident)
.map(DataAccessAtom::Key)
.parse(input)
}
fn i64_parse(input: Span) -> IResult<Span, i64> {
map_res(recognize(opt(tag("-")).precedes(digit1)), |s: Span| {
s.fragment().parse::<i64>()
})
.parse(input)
}
fn index_access(input: Span) -> IResult<Span, DataAccessAtom> {
delimited(tag("["), i64_parse, tag("]"))
.map(DataAccessAtom::Index)
.parse(input)
}
fn column_ref(input: Span) -> IResult<Span, Expr> {
tuple((ident, many0(alt((dot_property, index_access)))))
.map(|(head, rest)| Expr::Column {
head: DataAccessAtom::Key(head),
rest,
})
.parse(input)
}
fn ident(input: Span) -> IResult<Span, String> {
alt((bare_ident, escaped_ident))(input)
}
fn bare_ident(input: Span) -> IResult<Span, String> {
recognize(pair(satisfy(starts_ident), take_while(is_ident)))
.map(|span: Span| span.fragment().to_string())
.parse(input)
}
fn escaped_ident(input: Span) -> IResult<Span, String> {
expect_delimited(tag("["), quoted_string, tag("]"), |qc, r| {
qc.report_error_for("unterminated identifier")
.with_code_range(r, "")
.with_resolution("Insert a closing square bracket")
.send_report()
})
.parse(input)
}
/// Parses the basic unit of an expression
fn atomic(input: Span) -> IResult<Span, Expr> {
let num = digit1.map(|s: Span| data::Value::from_string(*s.fragment()));
let bool_lit = alt((
tag("true").map(|_| data::Value::Bool(true)),
tag("false").map(|_| data::Value::Bool(false)),
));
let null = tag("null").map(|_| data::Value::None);
let quoted_string_value = quoted_string.map(data::Value::Str);
let duration_value = duration.map(data::Value::Duration);
let value = alt((quoted_string_value, duration_value, num, bool_lit, null)).map(Expr::Value);
let parens = expect_delimited(tag("("), expr, tag(")"), |qc, r| {
qc.report_error_for("unterminated parenthesized expression")
.with_code_range(r, "unterminated parenthesized expression")
.with_resolution("Insert a right parenthesis to terminate this expression")
.send_report()
});
alt((if_op, fcall, value, column_ref, parens)).parse(input)
}
/// Parses an atomic expression with an optional unary prefix
fn unary(input: Span) -> IResult<Span, Expr> {
let (input, opt_op) = opt(unary_op)(input)?;
match opt_op {
None => atomic(input),
Some(op) => expect_fn(atomic, |qc, r| {
qc.report_error_for("expecting expression for unary operator")
.with_code_range(r, "-")
.send_report()
})
.map(|operand| Expr::Unary {
op: op.clone(),
operand: Box::new(operand.unwrap_or(Expr::Error)),
})
.parse(input),
}
}
/// Parses the comparison operators
fn comp_op(input: Span) -> IResult<Span, ComparisonOp> {
alt((
tag("==").map(|_| ComparisonOp::Eq),
tag("!=").map(|_| ComparisonOp::Neq),
tag("<>").map(|_| ComparisonOp::Neq),
tag(">=").map(|_| ComparisonOp::Gte),
tag("<=").map(|_| ComparisonOp::Lte),
tag(">").map(|_| ComparisonOp::Gt),
tag("<").map(|_| ComparisonOp::Lt),
))(input)
}
/// Parses the unary operators
fn unary_op(input: Span) -> IResult<Span, UnaryOp> {
tag("!").map(|_| UnaryOp::Not).parse(input)
}
fn muldiv_op(input: Span) -> IResult<Span, ArithmeticOp> {
alt((
tag("*").map(|_| ArithmeticOp::Multiply),
tag("/").map(|_| ArithmeticOp::Divide),
))(input)
}
/// Parses a chain of multiple/divide expressions
fn term(input: Span) -> IResult<Span, Expr> {
let (input, init) = unary(input)?;
let qc = &input.extra;
let retval = fold_many0(
pair(with_pos(muldiv_op).delimited_by(multispace0), opt(unary)).map(
|(pos_op, opt_right)| {
if let Some(right) = opt_right {
(pos_op.value, right)
} else {
qc.report_error_for("expecting an operand for binary operator")
.with_code_range(pos_op.range, "dangling binary operator")
.with_resolution("Add the operand or delete the operator")
.send_report();
(pos_op.value, Expr::Error)
}
},
),
|| init.clone(),
|left, (op, right)| Expr::Binary {
left: Box::new(left),
op: BinaryOp::Arithmetic(op),
right: Box::new(right),
},
)(input);
retval
}
/// Parses a chain of plus/minus expressions
fn arith_expr(input: Span) -> IResult<Span, Expr> {
let (input, init) = term(input)?;
let init = move || init.clone();
fold_many0(