-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathparsers.py
3237 lines (2927 loc) · 132 KB
/
parsers.py
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
# HV: Contains parsers for querying list of scans
from __future__ import print_function
from six import iteritems
from functools import reduce
from functional import *
import re, hvutil, operator, math, itertools, inspect, plotiterator, copy, numpy, plotutil, collections
haveQuanta = False
try:
import pyrap.quanta
haveQuanta = True
except ImportError:
pass
class token_type(object):
__slots__ = ['type', 'value', 'position']
# tokens must AT LEAST have a type. Most other things are optional
def __init__(self, tp, val=None, **kwargs):
self.type = tp
self.value = val
self.position = kwargs.get('position', -1)
def __str__(self):
return "(type={0}, val={1}, pos={2})".format(self.type, self.value, self.position)
def __repr__(self):
return str(self)
def D(x):
print(x)
return x
def DD(x):
def do_it(y):
print(x,y)
return y
return do_it
def mk_tokenizer(tokens, **env):
# run all the token regexps against the text at postion p
# and return a list of those that matched with their converted value(s)
def get_matchobjects(txt, p):
return map_(lambda mo_tp: (mo_tp[0], mo_tp[1](mo_tp[0], position=p, **env)),
filter(GetN(0),
map(lambda rx_tp: (rx_tp[0].match(txt, p), rx_tp[1]), tokens)))
#sep = "\n -> "
def do_tokenize(string):
pos = 0
while pos<len(string):
# Run all known regexps against the current string and filter out which one(s) matched
moList = get_matchobjects(string, pos)
if len(moList)==0:
raise RuntimeError("\n{0}\n{1:>{2}s}^\n{3} tokens matched here".format(string, "", pos, len(moList)))
# extract match-object and the token from the result list
(mo, tok) = moList[0]
pos += (mo.end() - mo.start())
# Ignore tokens that say they are nothing (e.g. whitespace)
if tok is not None:
yield tok
yield token_type(None, None)
return do_tokenize
# helper functions
def mk_number(val):
try:
return int(val)
except ValueError:
return float(val)
# transform a matched date/time object into MJD seconds
def mk_mjdsecs(mo, **kwargs):
if not haveQuanta:
raise RuntimeError("pyrap.quanta module not available for date/time to seconds functionality")
# we must have 'year', 'month' and 'day'
# 'h', 'm' and 's' are optional and default to 0
# We know that CASA's quantity parses
# day-month-yearThhHmmMss.sssS correctly
# so transform our input to that form
G = mo.group
# Be careful to not access groups that may not be present at all!
option = lambda group: G(group) if group in mo.groupdict() and mo.groupdict()[group] else 0
return pyrap.quanta.quantity(
"{0}-{1}-{2}T{3}H{4}M{5}S".format(G('day'), G('month'), G('year'), option('h'), option('m'), option('s'))
).get_value("s")
# Transform relative day time stamp and durations into seconds
def mk_seconds(mg, **kwargs):
rv = 0.0
secday = 86400
grps = mg.groupdict()
if 'd' in grps and mg.group('d'):
rv += float(mg.group('d'))*secday
if 'h' in grps and mg.group('h'):
rv += float(mg.group('h'))*3600.0
if 'm' in grps and mg.group('m'):
rv += float(mg.group('m'))*60.0
if 's' in grps and mg.group('s'):
rv += float(mg.group('s'))
if 'offset' in grps and mg.group('offset'):
rv += (int(mg.group('offset')) + (math.floor(float(kwargs.get('start', 0))/secday))) * secday
if 'neg' in grps and mg.group('neg'):
rv *= -1
return rv
resolver = lambda group: lambda mg, **env: env[mg.group(group)]
def mk_operator(which):
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv, '^':operator.pow,
'&&': operator.and_, '||': operator.or_, '!':operator.not_,
'and': operator.and_, 'or': operator.or_, 'not':operator.not_,
'in': lambda x, y: operator.contains(y, x), '=':operator.eq,
'<': operator.lt, '<=':operator.le, '>=':operator.ge, '>':operator.gt }
return ops[which]
# Token makers
token_def = lambda pattern, fn: (re.compile(pattern), fn)
ignore_t = lambda : lambda o, **k: None
keyword_t = lambda : lambda o, **k: token_type(o.group(0), **k)
simple_t = lambda tp : lambda o, **k: token_type(tp, **k)
value_t = lambda tp : lambda o, **k: token_type(tp, o.group(0), **k)
# extract a given match group
extract_t = lambda tp, g: lambda o, **k: token_type(tp, o.group(g), **k)
# xform = transform match group 0 [ie the whole regex match]
xform_t = lambda tp, f: lambda o, **k: token_type(tp, f(o.group(0)), **k)
# xformmg = transform the match object; ie you have access to all match groups
# xfrommge = same as previous but you have the environment passed in as well
xformmg_t = lambda tp, f: lambda o, **k: token_type(tp, f(o), **k)
xformmge_t = lambda tp, f: lambda o, **k: token_type(tp, f(o, **k), **k)
number_t = lambda : xform_t('number', mk_number)
operator_t = lambda tp : xform_t(tp, mk_operator)
datetime_t = lambda f : xformmge_t('datetime', f)
resolve_t = lambda tp, g: xformmge_t(tp, resolver(g))
#resolve_t = lambda tp, g: lambda o, **k: token_type(tp, resolver(g)(o, **k), **k)
# helper functions to help build token regexes
MAYBE = lambda x: r"("+x+r")?"
NAMED = lambda n, x: r"(?P<"+n+r">"+x+r")"
# Patterns for supported datetime formats
YMD = r"(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})"
DMY = r"(?P<day>\d{1,2})-(?P<month>([a-zA-Z]{3}|\d{1,2}))-(?P<year>\d{4})"
DMY_EUR = r"(?P<day>\d{1,2})/(?P<month>([a-zA-Z]{3}|\d{1,2}))/(?P<year>\d{4})"
SEP = r"[/T]"
TIME = r"(?P<h>\d{1,2}):(?P<m>\d{1,2}):(?P<s>\d{1,2}(\.\d*)?)"
HMS = r"(?P<h>\d{1,2})[hH](?P<m>\d{1,2})[mM](?P<s>\d{1,2}(\.\d*)?)[sS]"
RELDAY = r"(?P<offset>-?\d+)/"
# Float needs a decimal point somewhere in there, int never, number is either.
# note that numbers never include a leading '-' so parsers are responsible for
# supporting unary '-'
FLOAT = r"((\d+\.\d*)|\.\d+)([eE]-?\d+)?"
INT = r"\d+"
NUMBER = r"((\d+(\.\d*)?)|\.\d+)([eE]-?\d+)?"
# combine a date+time format and generate a token definition out of it
datetime_token = lambda date_fmt, time_fmt: token_def(date_fmt+SEP+time_fmt, datetime_t(mk_mjdsecs))
# Always nice to have. Note: if you want to support int and float at the same time
# care should be taken about the order. If you put 'int_token' before 'float_token'
# then you'll most likely never get a floating point token because the part
# before the decimal point will match the int token
float_token = lambda : token_def(FLOAT , xform_t('float', float))
int_token = lambda : token_def(INT , xform_t('int', int))
number_token = lambda : token_def(NUMBER, number_t())
def parse_scan(qry, **kwargs):
# Helper functions
def mk_intrange(txt):
return hvutil.expand_string_range(txt, rchar='-')
# take a string and make a "^...$" regex out of it,
# doing escaping of regex special chars and
# transforming "*" into ".*" and "?" into "."
# (basically shell regex => normal regex)
def pattern2regex(s):
s = reduce(lambda acc, x: re.sub(x, x, acc), [r"\+", r"\-", r"\."], s)
s = reduce(lambda acc, t_r: re.sub(t_r[0], t_r[1], acc), [(r"\*+", r".*"), (r"\?", r".")], s)
return re.compile(r"^"+s+"$")
def regex2regex(s):
flagmap = {"i": re.I, None:0}
mo = re.match(r"(.)(?P<pattern>.+)\1(?P<flag>.)?", s)
if not mo:
raise RuntimeError("'{0}' does not match the regex pattern /.../i?".format(s))
return re.compile(mo.group('pattern'), flagmap[mo.group('flag')])
# basic lexical elements
# These are the tokens for the tokenizer
tokens = [
# keywords
token_def(r"\b(to|not|where|limit)\b", keyword_t()),
# can't use 'keyword_t()' for the next one because we may need to accept whitespace between "order" and "by"
token_def(r"\b(asc|desc)\b", keyword_t()),
token_def(r"\border\s+by\b", simple_t('order by')),
token_def(r"\bin\b", operator_t('in')),
token_def(r"\b(and|or|in)\b", operator_t('relop')),
# Date + time formats
datetime_token(YMD, TIME),
datetime_token(YMD, HMS),
datetime_token(DMY, TIME),
datetime_token(DMY, HMS),
datetime_token(DMY_EUR, TIME),
datetime_token(DMY_EUR, HMS),
# Relative day offset - note: assume that the global variable
# 'start' is set correctly ...
token_def(RELDAY+TIME, datetime_t(mk_seconds)),
token_def(RELDAY+HMS, datetime_t(mk_seconds)),
# Time durations
token_def(r"(?P<neg>-)?(?P<d>\d+)d((?P<h>\d+)[hH])?((?P<m>\d+)[mM])?((?P<s>\d+(\.\d*)?)[sS])?", xformmg_t('duration', mk_seconds)),
token_def(r"(?P<neg>-)?(?P<h>\d+)[hH]((?P<m>\d+)[mM])?((?P<s>\d+(\.\d*)?)[sS])?", xformmg_t('duration', mk_seconds)),
token_def(r"(?P<neg>-)?(?P<m>\d+)[mM]((?P<s>\d+(\.\d*)?)[sS])?", xformmg_t('duration', mk_seconds)),
token_def(r"(?P<neg>-)?(?P<s>\d+(\.\d*)?)[sS]", xformmg_t('duration', mk_seconds)),
# regex
token_def(r"/[^/]+/i?", xform_t('regex', regex2regex)),
token_def(r"[0-9]+-[0-9]+(:[0-9]+)?", xform_t('irange', mk_intrange)),
float_token(),
int_token(),
# Operators that just stand for themselves
#token_def("~", simple_t('regexmatch')),
token_def(r"(~|\blike\b)", xform_t('regexmatch', lambda o, **k: lambda x, y: not re.match(y, x) is None)),
token_def(r"(<=|>=|=|<|>)", operator_t('compare')),
token_def(r"-|\+|\*|/", operator_t('operator')),
token_def(r"\(", simple_t('lparen')),
token_def(r"\)", simple_t('rparen')),
token_def(r"\[", simple_t('lbracket')),
token_def(r"\]", simple_t('rbracket')),
token_def(r",", simple_t('comma')),
# Textual stuff
token_def(r"\$(?P<sym>[a-zA-Z][a-zA-Z_]*)", resolve_t('external', 'sym')),
token_def(r"'[^']*'", value_t('literal')),
token_def(r"[:@\#%!\.a-zA-Z0-9_?|]+", value_t('text')),
token_def(r"\s+", ignore_t())
]
tokenizer = mk_tokenizer(tokens, **kwargs)
# The output of the parsing is a filter function that returns
# True or False given a scan object
#next = lambda s: s.next()
tok = lambda s: s.token
tok_tp = lambda s: s.token.type
tok_val = lambda s: s.token.value
###### Our grammar
# query = modifier [ 'where' condition ['order by' sorting ] ['limit' int] ] eof
# modifier = expr 'to' expr
# expr = term '+' term | term '-' term | term '*' term | term '/' term | '(' expr ')'
# term = duration | number | property | external
# duration = \d+ 'd'[\d+ 'h'][\d+ 'm'] [\d+ ['.' \d* ] 's'] |
# \d+ 'h'[\d+ 'm'] [\d+ ['.' \d* ] 's'] |
# \d+ 'm' [\d+ ['.' \d* ] 's'] |
# \d+ ['.' \d* ] 's'
# number = int|float
# property = alpha char {alpha char | digit | '_'} # will get property from scan object
# external = '$' property # will look up value of property in global namespace
# condition = condexpr {relop condexpr} | 'not' condexpr | '(' condexpr ')'
# sorting = sortterm {',' sortterm}
# sortterm = identifier ['asc','desc' ]
# condexpr = property '~' (regex|text) | property compare expr | property 'in' list
# compare = '=' | '>' | '>=' | '<' | '<=' ;
# relop = 'and' | 'or' ;
# list = '[' [value {',' value}] ']'
# value = anychar {anychar}
# regex = '/' {anychar - '/'} '/' ['i'] ('i' is the case-insensitive match flag)
# identifier = alpha {character}
# anychar = character | symbol
# character = alpha | digit
# alpha = [a-zA-Z_] ;
# digit = [0-9] ;
# query = expr 'to' expr [ 'where' condition ] eof
def parse_query(s):
if tok(s).type is None:
raise SyntaxError("empty query")
# parse the scan start/end time modification function first
perscan_f = parse_modifier(s)
# if the parse left off at the 'where' keyword, we know what to do
# note: the 'where' clause is optional and defaults to "all scans"
# WHERE
where = tok(s)
filter_f = parse_condition(next(s)) if where.type=='where' else lambda x: True
# "ORDER BY"
orderby = tok(s)
if orderby.type=='order by':
# only allow comma separated list of identifiers
# 'parse_sort_list' will return a list of sort functions, in the order
# in they were given
sortlist = parse_sort_list(next(s))
if not sortlist:
raise SyntaxError("No list of sort keys found (%s)" % tok(s))
# good, 'sortlist' is a list of sort functions that need to be applied
# on the list of filtered items
orderby.value = lambda x: reduce(lambda acc, sortfn: sortfn(acc), sortlist, x)
else:
# no sorting
orderby.value = identity
# "LIMIT"
limit = tok(s)
if limit.type=='limit':
# we MUST be followed by an int
next(s)
ival = tok(s)
if ival.type!='int':
raise SyntaxError("Only an integer is allowed after limit, not %s" % ival)
# consume the integer
next(s)
count = itertools.count()
limit.value = lambda x: itertools.takewhile(lambda obj: next(count)<ival.value, x)
else:
limit.value = identity
# the only token left should be 'eof' AND, after consuming it,
# the stream should be empty. Anything else is a syntax error
try:
if tok(s).type is None:
next(s)
except StopIteration:
return (perscan_f, compose(List, limit.value, orderby.value, Filter(filter_f)))
raise SyntaxError("Tokens left after parsing %s" % tok(s))
# modifier = expr 'to' expr
def parse_modifier(s):
# we require two functions to be generated, the start_time_fn (before 'to')
# and the end_time_fn (after 'to' ...)
depth = s.depth
start_time_fn = parse_expr(s)
#start_time_fn = parse_expr(s, None)
if s.depth!=depth:
raise SyntaxError("Unbalanced parenthesis %s" % tok(s))
# we now MUST see the 'to' keyword
to = tok(s)
if to is None or to.type!='to':
raise SyntaxError("Unexpected token %s (expected 'to' keyword)" % tok(s))
# do not forget to consume the 'to' keyword ...
depth = s.depth
end_time_fn = parse_expr(next(s))
if s.depth!=depth:
raise SyntaxError("Unbalanced parentheses %s (expect depth %d, found %d)" % (tok(s), depth, s.depth))
def this_fn(scan):
s_time = start_time_fn(scan)
e_time = end_time_fn(scan)
if e_time<s_time:
raise RuntimeError("Scan time selection error: end time is before start time in scan\n {0}".format(scan))
return (s_time, e_time)
return this_fn
#return lambda scan: (start_time_fn(scan), end_time_fn(scan))
# expr = term | expr '+' expr | expr '-' expr | expr '*' expr | expr '/' expr | '(' expr ')' | '-' expr
def parse_expr(s, unary=False):
t = tok(s)
depth = s.depth
if t.type in ['lparen', 'rparen']:
lterm = parse_paren(s)
elif t.type=='operator' and t.value is mk_operator('-'):
# unary '-'
tmpexpr = parse_expr(next(s), unary=True)
lterm = lambda scan: operator.neg( tmpexpr(scan) )
else:
lterm = parse_term(s)
# If we see an operator, we must parse the right-hand-side
# (our argument is the left-hand-side
# Well ... not if we're doing unary parsing!
# if we saw unary '-' then we should parse parens and terms up until
# the next operator
oper = tok(s)
if oper.type=='operator':
if unary:
return lterm
if lterm is None:
raise SyntaxError("No left-hand-side to operator %s" % oper)
rterm = parse_expr(next(s))
if rterm is None:
raise SyntaxError("No right-hand-side to operator %s" % oper)
return lambda scan: oper.value(lterm(scan), rterm(scan))
elif oper.type in ['int', 'float', 'duration', 'datetime']:
# negative numbers as right hand side are not negative numbers
# but are operator '-'!
# so, subtracting a number means adding the negative value (which we already
# have god)
# Consume the number and return the operator add
next(s)
return lambda scan: operator.add(lterm(scan), oper.value)
# neither parens, terms, operators?
return lterm
def parse_paren(s):
lparen = tok(s)
if lparen.type!='lparen':
raise RuntimeError("Entered parse_paren w/o left paren but %s" % lparen)
depth = s.depth
s.depth = s.depth + 1
# recurse into parsing the expression - and do NOT forget to consume the lparen!
expr = parse_expr(next(s))
# now we should be back at the same depth AND we should be seeing rparen
rparen = tok(s)
if rparen.type=='rparen':
s.depth = s.depth - 1
next(s)
return expr
# term = duration | number | property | external
def parse_term(s):
term = tok(s)
# The easy bits first
if term.type in ['int', 'float', 'external', 'duration', 'datetime', 'text']:
if term.type=='text':
def attrib_or_value(scan):
if hasattr(scan, term.value):
return getattr(scan, term.value)
else:
return term.value
rv = attrib_or_value
else:
rv = lambda scan: term.value
# all's well - eat this term
next(s)
return rv
elif term.type=='literal':
# ok, allowed to consume it
next(s)
# note that we strip the leading and closing single quote
rv = lambda scan: term.value[1:-1]
return rv
return None
# condition = condexpr {relop condexpr} | 'not' condition | '(' condition ')'
# relop = 'and' | 'or' ;
def parse_condition(s):
token = tok(s)
# Recurse if we need to
if token.type in ['lparen', 'rparen']:
lterm = parse_paren_condition(s)
# 'not' expr
elif token.type=='not':
# parse the next expr and negate it
# we MUST have a next one
condition = parse_condition(next(s))
if condition is None:
raise SyntaxError("Missing expression after 'not' %s" % condition)
lterm = lambda scan: operator.not_( condition(scan) )
else:
# it must be a condexpr
lterm = parse_cond_expr(s)
# If we now see a relop, we have to parse another condition
relop = tok(s)
if relop.type!='relop':
return lterm
# consume the relop & parse the condition
rterm = parse_condition(next(s))
if lterm is None:
raise SyntaxError("Missing left-hand-condition to relational operator (%s)", relop)
if rterm is None:
raise SyntaxError("Missing right-hand-condition to relational operator (%s)", relop)
# and return the combined operation
return lambda scan: relop.value(lterm(scan), rterm(scan))
# condexpr = expr '~' (regex|text) | expr compare expr | expr 'in' list
# compare = '=' | '>' | '>=' | '<' | '<=' ;
def parse_cond_expr(s):
token = tok(s)
# No matter what, we have a left and a right hand side
# separated by an operator
lterm = parse_expr(s)
if lterm is None:
raise SyntaxError("Failed to parse left-hand-term of cond_expr (%s)" % tok(s))
# Now we must see a comparator
compare = tok(s)
if not compare.type in ['compare', 'regexmatch', 'in']:
raise SyntaxError("Expected a comparison operator, regex match or 'in' keyword, got %s" % compare)
# consume the comparison
next(s)
# do some processing based on the type of operator
if compare.type=='in':
rterm = parse_list(s)
elif compare.type=='compare':
rterm = parse_expr(s)
else:
# must've been regexmatch
rterm = parse_rx(s)
# it better exist
if rterm is None:
raise SyntaxError("Failed to parse right-hand-term of cond_expr (%s)" % tok(s))
return lambda scan: compare.value(lterm(scan), rterm(scan))
def parse_paren_condition(s):
lparen = tok(s)
if lparen.type!='lparen':
raise RuntimeError("Entered parse_paren_condition w/o left paren but %s" % lparen)
depth = s.depth
s.depth = s.depth + 1
# recurse into parsing the expression - and do NOT forget to consume the lparen!
expr = parse_condition(next(s))
# now we should be back at the same depth AND we should be seeing rparen
rparen = tok(s)
if rparen.type=='rparen':
s.depth = s.depth - 1
next(s)
return expr
def parse_rx(s):
# we accept string, literal and regex and return an rx object
rx = tok(s)
if not rx.type in ['regex', 'text', 'literal']:
raise SyntaxError("Failed to parse string matching regex (not regex, text or literal but %s)" % rx)
# consume the token
next(s)
if rx.type=='literal':
# extract the pattern from the literal (ie strip the leading/trailing "'" characters)
rx.value = rx.value[1:-1]
if rx.type in ['text', 'literal']:
rx.value = pattern2regex(rx.value)
return lambda scan: rx.value
def parse_list(s):
bracket = tok(s)
if bracket.type != 'lbracket':
raise SyntaxError("Expected list-open bracket ('[') but found %s" % bracket)
rv = []
# keep eating text + ',' until we read 'rbracket'
next(s)
while tok(s).type!='rbracket':
# if we end up here we KNOW we have a non-empty list because
# the next token after '[' was NOT ']'
# Thus if we need a comma, we could also be seeing ']'
needcomma = len(rv)>0
#print " ... needcomma=",needcomma," current token=",tok(s)
if needcomma:
if tok(s).type=='rbracket':
continue
if tok(s).type!='comma':
raise SyntaxError("Badly formed list at {0}".format(tok(s)))
# and eat the comma
next(s)
# now we need a value. 'identifier' is also an acceptable blob of text
rv.extend( parse_list_item(s) )
#print "parse_list: ",rv
# and consume the rbracket (if not rbracket a syntax error is raised above)
next(s)
return lambda scan: rv
# always returns a list-of-items; suppose the list item was an irange
def parse_list_item(s):
t = tok(s)
# current token must be 'text' or 'irange'
if not t.type in ['text', 'irange', 'int', 'float', 'literal']:
raise SyntaxError("Failure to parse list-item {0}".format(t))
next(s)
# for a literal, strip the leading and closing single quote
if t.type == 'literal':
t.value = t.value[1:-1]
return t.value if t.type == 'irange' else [t.value]
# attribute list = identifier {',' identifier}
def parse_sort_list(s):
rv = []
rxAttribute = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*$")
while True:
item = tok(s)
if item.type!='text':
raise SyntaxError("attribute list may only contain strings, found %s" % item)
if not rxAttribute.match(item.value):
raise SyntaxError("%s is not a valid attribute name" % item)
# Peek at the next token. If it's asc/desc take that into account
next(s)
order = tok(s)
if order.type in ['asc', 'desc']:
# consume it
next(s)
else:
order.type = 'asc'
# create a sorting function
def mk_sf(attr, order):
def do_it(x):
return sorted(x, key=operator.attrgetter(attr), reverse=(order=='desc'))
return do_it
rv.append( mk_sf(item.value, order.type) )
#if we don't see a comma next, we break
if tok(s).type!='comma':
break
# consume the comma
next(s)
# primary sort key is now first in list but for the sorting to work in steps
# (see https://wiki.python.org/moin/HowTo/Sorting ) we must apply the sorting
# functions in reverse order
return reversed(rv)
class state_type:
def __init__(self, tokstream):
self.tokenstream = tokstream
self.depth = 0
next(self)
def __next__(self):
self.token = next(self.tokenstream)
return self
next = __next__
tokenizer = mk_tokenizer(tokens, **kwargs)
return parse_query(state_type(tokenizer(qry)))
# Time (range) grammar - we must support some arithmetic
#
# timerange = expr { 'to' ('+' duration | expr )}
# expr = term '+' term | term '-' term | term '*' term | term '/' term | '(' expr ')'
# term = number | identifier | datetime | duration | reltime
# datetime = year '/' month '/' day [T/] timestamp | day '-' month '-' year [T/] timestamp | day '-' monthstr '-' year [T/] timestamp
# reltime = {'-'} digit {digit} '/' timestamp
# reltime = {'-'} digit {digit} '/' duration
# year = 4 * digit
# month = 2 * digit
# monthstr = 3 * alpha char
# day = 2 * digit
# timestamp = digit {digit} [hH] digit {digit} [mM] digit {digit} {'.' digits } [sS]) |
# digit {digit} ':' digit {digit} ':' digit {digit} {'.' digits}
# duration = number [hH] { number [mM] { number ['.' number] [sS] } } | number [mM] { number ['.' number] [sS] } | number ['.' number] [sS]
# scan prop = 'scan' digits '.' identifier
# number = {'-'} {[0-9]+}{'.'}[0-9]+{[eE]{-}[0-9]+}
# identifier = alpha char {alpha char | digit | '_' }
# digits = digit {digit}
# digit = [0-9]
# alpha char = [a-zA-Z]
SEC = r"(?P<s>\d+(\.\d*)?)[sS]"
MIN = r"(?P<m>\d+)[mM]"
HR = r"(?P<h>\d+)[hH]"
DAY = r"(?P<d>\d+)d"
DUR4 = DAY+MAYBE(HR)+MAYBE(MIN)+MAYBE(SEC)
DUR3 = HR+MAYBE(MIN)+MAYBE(SEC)
DUR2 = MIN+MAYBE(SEC)
DUR1 = SEC
def parse_time_expr(txt, **env):
# Helper functions
# basic lexical elements
# These are the tokens for the tokenizer
tokens = [
# keywords
token_def(r"\bto\b", keyword_t()),
# Date + time formats
datetime_token(YMD, TIME),
datetime_token(YMD, HMS),
datetime_token(DMY, TIME),
datetime_token(DMY, HMS),
datetime_token(DMY_EUR, TIME),
datetime_token(DMY_EUR, HMS),
# Relative day offset - note: assume that the global variable
# 'start' is set correctly ...
token_def(RELDAY+TIME, datetime_t(mk_seconds)),
token_def(RELDAY+HMS, datetime_t(mk_seconds)),
# Time durations
token_def(RELDAY+DUR3, datetime_t(mk_seconds)),
token_def(RELDAY+DUR2, datetime_t(mk_seconds)),
token_def(RELDAY+DUR1, datetime_t(mk_seconds)),
token_def(DUR4, xformmg_t('duration', mk_seconds)),
token_def(DUR3, xformmg_t('duration', mk_seconds)),
token_def(DUR2, xformmg_t('duration', mk_seconds)),
token_def(DUR1, xformmg_t('duration', mk_seconds)),
# Operators and semantic elements that just stand for themselves
token_def(r"-|\+|\*|/", operator_t('operator')),
token_def(r"\(", simple_t('lparen')),
token_def(r"\)", simple_t('rparen')),
token_def(r',', simple_t('comma')),
# we don't care about int's or float's - any number we'll accept
number_token(),
token_def(r"\$(?P<sym>[a-zA-Z][a-zA-Z_]*)", resolve_t('external', 'sym')),
token_def(r"\s+", ignore_t())
]
# shorthands that work on the parser state 's'
#next = lambda s: s.next()
tok = lambda s: s.token
tok_tp = lambda s: s.token.type
tok_val = lambda s: s.token.value
# timeranges = timerange {',' timerange}
# timerange = expr ['to' expr)]
def parse_time_ranges(s):
rv = []
while True:
rv.append( parse_time_range(s) )
# Check for more time ranges
nxt = tok(s)
if nxt.type=='comma':
# consume the comma and continue
next(s)
continue
break
# Ok, we should now see 'eof' and an empty stream
try:
if tok(s).type is None:
next(s)
except StopIteration:
return rv
raise SyntaxError("Tokens left after parsing %s" % tok(s))
# timerange = expr ['to' expr ]
def parse_time_range(s):
# we require two functions to be generated, the start_time_fn (before 'to')
# and the end_time_fn (after 'to' ...)
depth = s.depth
start_time = parse_expr(s)
if s.depth!=depth:
raise SyntaxError("Unbalanced parenthesis %s" % tok(s))
if start_time is None:
raise SyntaxError("Missing start-time expression %s" % tok(s))
# If we don't see the 'to' keyword, it's a single time stamp
to = tok(s)
if to.type!='to':
return (start_time, start_time)
# insert the current rterm value in the environment such that
# the 'end_time' may use "+ duration"
env['$#parsed:start^time#$'] = start_time
# parse the end time after consuming the 'to' keyword
depth = s.depth
end_time = parse_expr(next(s))
# remove the value from the environment again
del env['$#parsed:start^time#$']
if s.depth!=depth:
raise SyntaxError("Unbalanced parentheses %s (expect depth %d, found %d)" % (tok(s), depth, s.depth))
if end_time is None:
raise SyntaxError("Missing end-time expression %s" % tok(s))
if end_time<start_time:
t = tok(s)
raise RuntimeError("{0}\n{1:>{2}s}^\nend time is before start time here".format(txt, "", len(txt) if t.position<0 else t.position))
return (start_time, end_time)
# expr = term | expr '+' expr | expr '-' expr | expr '*' expr | expr '/' expr | '(' expr ')' | '-' expr
def parse_expr(s, unary=False):
t = tok(s)
depth = s.depth
if t.type in ['lparen', 'rparen']:
lterm = parse_paren(s)
elif t.type=='operator' and t.value is mk_operator('-'):
# unary '-'
tmpexpr = parse_expr(next(s), unary=True)
lterm = operator.neg( tmpexpr )
elif t.type=='operator' and t.value is mk_operator('+'):
# unary '+' - may be followed by an expression; we add the parsed time
# to whatever the start time was
next(s)
duration = parse_expr(s)
return env['$#parsed:start^time#$'] + duration
else:
lterm = parse_term(s)
# If we see an operator, we must parse the right-hand-side
# (our argument is the left-hand-side
# Well ... not if we're doing unary parsing!
# if we saw unary '-' then we should parse parens and terms up until
# the next operator
oper = tok(s)
if oper.type=='operator':
if unary:
return lterm
if lterm is None:
raise SyntaxError("No left-hand-side to operator %s" % oper)
rterm = parse_expr(next(s))
if rterm is None:
raise SyntaxError("No right-hand-side to operator %s" % oper)
return oper.value(lterm, rterm)
elif oper.type in ['int', 'float', 'duration', 'datetime']:
# negative numbers as right hand side are not negative numbers
# but are operator '-'!
# so, subtracting a number means adding the negative value (which we already
# have god)
# Consume the number and return the operator add
next(s)
return operator.add(lterm, oper.value)
# neither parens, terms, operators?
return lterm
def parse_paren(s):
lparen = tok(s)
if lparen.type!='lparen':
raise RuntimeError("Entered parse_paren w/o left paren but %s" % lparen)
depth = s.depth
s.depth = s.depth + 1
# recurse into parsing the expression - and do NOT forget to consume the lparen!
expr = parse_expr(next(s))
# now we should be back at the same depth AND we should be seeing rparen
rparen = tok(s)
if rparen.type=='rparen':
s.depth = s.depth - 1
next(s)
return expr
# term = duration | number | external
def parse_term(s):
term = tok(s)
# The easy bits first
if term.type in ['number', 'external', 'duration', 'datetime']:
# all's well - eat this term
next(s)
return term.value
return None
class state_type:
def __init__(self, tokstream):
self.tokenstream = tokstream
self.depth = 0
next(self)
def __next__(self):
self.token = next(self.tokenstream)
return self
next = __next__
tokenizer = mk_tokenizer(tokens, **env)
return parse_time_ranges(state_type(tokenizer(txt)))
# Parse a simple duration (sort of VEX format):
# ...y..d..h..m....s
# there must be at least one unit present, trailing fields after the highest order unit are optional.
# only accepts units in this order; e.g. cannot say 10s1h
MINf = r"(?P<m>\d+(\.\d*)?)[mM]"
HRf = r"(?P<h>\d+(\.\d*)?)[hH]"
DAYf = r"(?P<d>\d+(\.\d*)?)d"
DUR4f = DAYf+MAYBE(HRf)+MAYBE(MINf)+MAYBE(SEC)
DUR3f = HRf+MAYBE(MINf)+MAYBE(SEC)
DUR2f = MINf+MAYBE(SEC)
def parse_duration(txt, **env):
# Helper functions
# basic lexical elements
# These are the tokens for the tokenizer
tokens = [
# Time durations
token_def(DUR4f, xformmg_t('duration', mk_seconds)),
token_def(DUR3f, xformmg_t('duration', mk_seconds)),
token_def(DUR2f, xformmg_t('duration', mk_seconds)),
token_def(DUR1, xformmg_t('duration', mk_seconds)),
token_def(r"\S+", lambda o, **kwargs: token_type('gunk', o.group(0)))
]
# shorthands that work on the parser state 's'
#next = lambda s: s.next()
tok = lambda s: s.token
tok_tp = lambda s: s.token.type
tok_val = lambda s: s.token.value
# duration = ..y..d..h..m..s
def parse_time_duration(s):
dur = tok(s)
if dur.type!='duration':
raise SyntaxError("This is not a duration - %s" % dur)
next(s)
try:
if tok(s).type is None:
next(s)
except StopIteration:
return dur.value
raise SyntaxError("Tokens left after parsing %s" % tok(s))
class state_type:
def __init__(self, tokstream):
self.tokenstream = tokstream
self.depth = 0
next(self)
def __next__(self):
self.token = next(self.tokenstream)
return self
next = __next__
tokenizer = mk_tokenizer(tokens, **env)
return parse_time_duration(state_type(tokenizer(txt)))
########################################################################################################
#
# data set expression parser
# allows manipulation of results of plotiterator - e.g. differencing
#
#########################################################################################################
# <dscmd> = 'store' {<expr>} 'as' <id> | 'load' <expr>
# <expr> = <expr> '+' <term> | <expr> '-' <term> | <term>
# <term> = <term> '*' <factor> | <term> '/' <factor> | <factor>
# <factor> = <exponent> '^' <factor> | <exponent>
# <exponent> = '-' <exponent> | <final>
# <final> = <number> | <id> | <id> '(' <arglist> ')' | '(' <expr> ')' | <id> '[' <subscript> ']'
# <arglist> = <empty> | <expr> {',' <expr> }
# <subscript> = <filter> {',' <filter> }
# <filter> = <attribute> '=' <value>
# <attribute> = 'p' | 'ch' | 'sb' | 'src' | 'time' | 'bl' | 'fq'
# 'P' | 'CH' | 'SB' | 'SRC' | 'TIME' | 'BL' | 'FQ'
# <value> = <int> | <alnum> # may/should/will depend on type of attribute!
#
# <number> = <int> | <float>
# <int> = [0-9]+
# <float> = [0-9]+'.'[0-9]* | '.'[0-9]+
# <id> = <alnum>{'.'<alnum>}
# <alnum> = [a-zA-Z_][a-zA-Z0-9_]*
methodwrappert = type({}.__delitem__)
def isAttr(o):
# in fact, 'inspect.is<predicate>' predicates are useless. They still return all
# the members of e.g. a "dict()". Because all of the methods of 'dict' are now
# of type <method-wrapper>. Gah!
#return not (inspect.isfunction(o) or inspect.ismethod(o))
return not (inspect.isbuiltin(o) or o is methodwrappert)
def copy_attributes(outp, inp):
drap(lambda a_v: setattr(outp, a_v[0], a_v[1]), \
map(lambda a_tp: (a_tp[0], getattr(inp, a_tp[0])), \
filter(lambda nm_tp: not nm_tp[0].startswith('__'), inspect.getmembers(inp, isAttr))))
return outp
def ds_flat_filter(value, tp=None, subscript=None):
rv = copy_attributes(plotutil.Dict(), value)
(mklabf, subquery) = (identity, const(True)) if subscript is None else subscript
for ds in (value.keys() if tp is None else filter(lambda k: k.TYPE==tp, value.keys())):
# Do we accept this dataset?
if not subquery(ds):
continue
# if anames is set, it means we've filtered/subindexed so we must create a new label with
# the indicated anames set to None [such that the crossmatching on those won't fail]
nds = mklabf(ds)
rv[nds] = value[ds].sort()
return rv
def ds_key_filter(value, keys):
rv = copy_attributes(plotutil.Dict(), value)
for k in keys:
rv[k] = value[k]
return rv
dictType = type({})
#isDataset = lambda x: isinstance(x, plotutil.plt_dataset)
isDataset = lambda x: isinstance(x, dictType)
def normal_apply(l, f, r):
return (None, (l._xval, f(l._yval.data, r._yval.data)))
def shortest_apply(l, f, r):
n = min(len(l._yval.data), len(r._yval.data))
return ("Truncated to {0} elements".format(n), (l._xval.data[:n], f(l._yval.data[:n], r._yval.data[:n])))
isect_table = {
# ( <lengths equal>, <one of 'm has length '1'>)
(True, False): normal_apply, # when both lengths are equal it doesn't matter how long
(True, True): normal_apply, # ..
(False, True): normal_apply, # if unequal lengths but one of'm has is length '1'
(False, False): shortest_apply # only apply to first 'n' elements
}
# args = (cond1(a), msg1(A)), (cond2(a), msg2(A)), ...
# i.e. tuples with two elements: a function to test the result and a function to produce
# the error message. Both functions get passed the full plot dataset
#
# Note: processing stops after the first test fails
def maybe_warn(a, *args):
for (cond, msg) in args:
if cond(a):
print(msg(a))
break
return a
def do_isect(d0, f, d1):
# we know both d0 and d1 are flattened datasets
# so we must iterate over the set of identical keys
# for each key we apply the operation to the y-part of the datasets
def app(acc, key):
# make sure they're numarrays
# [note: .as_numarray() does not create a new object, just returns 'self']
ds0 = d0[key]
ds1 = d1[key]
l0 = len(ds0._yval)
l1 = len(ds1._yval)
# compare lengths (...) and decide what to do
(msg, res) = isect_table[(l0==l1, l0==1 or l1==1)](ds0, f, ds1)
if msg is not None:
print("{0}: {1}".format(key, msg))