-
Notifications
You must be signed in to change notification settings - Fork 6
/
vnl-filter
executable file
·1831 lines (1438 loc) · 58.2 KB
/
vnl-filter
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
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long qw(:config no_getopt_compat bundling);
use List::Util 'max';
use List::MoreUtils qw(any all);
use FindBin '$RealBin';
use lib "$RealBin/lib";
use Vnlog::Util 'get_unbuffered_line';
use Text::Balanced 'extract_bracketed';
use feature qw(say state);
my $usage = <<EOF;
$0 [--has c0,c1,...] [-p c3,+c4,sum=c5+c6,rel(c7)] [match_expr] [match_expr] ...
Other available options:
--list-columns
--sub 'f(x) { .... return ... }'
--sub-abs
--eval expr
--begin expr
--end expr
--noskipempty
--skipcomments
--dumpexprs
--perl
--unbuffered
--stream
-A/-B/-C
This tool is a nicer 'awk' that reads and writes vnlog. Unlike awk,
vnl-filter refers to columns by name, not index.
Columns are selected with -p; if omitted, all columns are selected.
Arbitrary expressions can be output with 'vnl-filter -p f=...'. For
instance, to output columns 'a', 'b' and their sum:
vnl-filter -p 'a,b,sum=a+b'
Rows are selected with match expressions given on the commandline. To select
all rows after a certain time, and within a certain temperature range, do:
vnl-filter 'time > 100' 'temp > 20 && temp < 30'
By default, this tool generates an awk script that's then interpreted by
mawk. Although it is slower, perl can be used instead by passing --perl.
This makes no difference in output in most cases, but the various
expressions would be evaluated by perl, which is often useful, especially
for anything non-trivial.
--unbuffered flushes each line after each print. Useful for streaming data.
--stream is a synonym for "--unbuffered"
-A N/ -B N / -C N prints N lines of context after/before/around all records
matching the given expressions. Works just like in the 'grep' tool
For more information, please read the manpage.
EOF
if(! @ARGV)
{
die $usage;
}
# by default we do skip empty records
my %options = (skipempty => 1);
GetOptions(\%options,
"list-columns|l",
"has=s@",
"pick|print|p=s@",
"eval=s",
"after-context|A=i",
"before-context|B=i",
"context|C=i",
"function|sub=s@",
"function-abs|sub-abs",
"begin|BEGIN=s",
"end|END=s",
"skipempty!",
"skipcomments!",
"dumpexprs!",
"perl",
"unbuffered",
"stream",
"help") or die($usage);
if( defined $options{help} )
{
print $usage;
exit 0;
}
$options{has} //= [];
$options{pick} //= [];
$options{unbuffered} = $options{unbuffered} || $options{stream};
# anything remaining on the commandline are 'matches' expressions
$options{matches} = \@ARGV;
if( defined $options{eval} )
{
$options{skipcomments} = 1;
}
if( defined $options{eval} && @{$options{pick}} )
{
say STDERR "--eval is given, so no column selectors should be given also";
die $usage;
}
if( defined $options{context} &&
(defined $options{'before-context'} ||
defined $options{'after-context'}) )
{
say STDERR "-C is exclusive with -A and -B";
die $usage;
}
my $any_context_stuff =
$options{'after-context'} ||
$options{'before-context'} ||
$options{'context'};
if( $any_context_stuff && $options{eval} )
{
say STDERR "--eval is exclusive with -A/-B/-C";
die $usage;
}
my $NcontextBefore = ($options{'before-context'} || $options{'context'}) // 0;
my $NcontextAfter = ($options{'after-context'} || $options{'context'}) // 0;
# parse the , in $options{has} and $options{pick}. In --pick use the fancy
# ()-respecting version of split
@{$options{has}} = map split(/,/, $_), @{$options{has}};
@{$options{pick}} = map split_on_comma_respect_parens($_), @{$options{pick}};
# any requested columns preceded with '+' go into --has. And I strip out the '+'
for my $ipick(0..$#{$options{pick}})
{
# handle extra column syntax here
if( ${$options{pick}}[$ipick] =~ /^\+(.+)/ )
{
${$options{pick}}[$ipick] = $1;
push @{$options{has}}, ${$options{pick}}[$ipick];
}
}
my @picked_exprs_named = @{$options{pick}};
my @must_have_col_names = @{$options{has}};
my @must_have_col_indices_input;
# if no columns requested, just print everything
if( !@picked_exprs_named &&
!$options{'list-columns'} &&
!@must_have_col_names &&
!@{$options{matches}} &&
!defined $options{eval} )
{
if($options{dumpexprs})
{
say "--dumpexprs: No-op special case; printing everything, modulo --skipcomments, --noskipempty";
exit 0;
}
my $gotlegend;
while(<STDIN>)
{
if( $options{skipempty} )
{
next if /^ \s* - (?: \s+ - )* \s* $/x;
}
if( $options{skipcomments})
{
# always skip hard comments
next if /^\s*(?:#[#!]|#\s*$|$)/p;
# skip a single comment only if we need a legend still
if( /^\s*#/)
{
next if $gotlegend;
$gotlegend = 1;
}
}
print;
flush STDOUT if $options{unbuffered};
}
exit 0;
}
my @colnames_output;
# input column-name to index map. This always maps to a listref of indices, even
# if I only have a single index
my %colindices_input;
my $colidx_needed_max = -1;
# awk or perl strings representing stuff to output. These are either simple
# column references (such as $1), or more complex expressions
my @langspecific_output_fields;
# How many rel(),diff(),... calls we have. I generate code based on this
my @all_specialops = qw(rel diff sum prev latestdefined);
my %specialops;
for my $what (@all_specialops)
{
$specialops{$what} = {N => 0,
outer => []};
}
# Loop searching for the legend.
#
# Here instead of using while(<STDIN>) we read one byte at a time. This means
# that as far as the OS is concerned we never read() past our line. And when we
# exec() to awk, all the data is available. This is inefficient, but we only use
# this function to read up to the legend, which is fine.
#
# Note that perl tries to make while(<STDIN>) work by doing an lseek() before we
# exec(), but if we're reading a pipe, this can't work
while(defined ($_ = get_unbuffered_line(*STDIN)))
{
# I pass through (don't treat as a legend) ## comments and #! shebang and
# empty lines and # comments without anything else.
if(/^\s*(?:#[#!]|#\s*$|$)/p)
{
if(!$options{skipcomments} && !$options{dumpexprs} && !$options{'list-columns'})
{
print;
flush STDOUT if $options{unbuffered};
}
next;
}
if( /^\s*#\s*/p )
{
chomp;
# we got a legend line
my @cols_all_legend_input = split ' ', ${^POSTMATCH}; # split the field names (sans the #)
if($options{'list-columns'})
{
for my $c (@cols_all_legend_input)
{
say $c;
}
exit 0;
}
foreach my $idx (0..$#cols_all_legend_input)
{
$colindices_input{$cols_all_legend_input[$idx]} //= [];
push @{$colindices_input{$cols_all_legend_input[$idx]}}, $idx;
}
# each element is a tuple representing a picked field:
# (output_field, colidx_needed_max_here, colname_output)
my @picked_fields;
# If we weren't asked for particular columns, take them all. This isn't
# a no-op because we can have --has
if( @picked_exprs_named )
{
foreach my $i_picked_exprs_named (0..$#picked_exprs_named)
{
my $accept = sub
{
my ($expr, $name, $dupindex) = @_;
push @picked_fields,
[ expr_subst_col_names($options{perl} ? 'perl' : 'awk',
$expr,
$dupindex),
$name // $expr ];
};
my $acceptExactMatch = sub
{
my ($picked_expr, $name) = @_;
if (defined $colindices_input{$picked_expr})
{
for my $dupindex (0..$#{$colindices_input{$picked_expr}})
{
$accept->( $picked_expr, $name, $dupindex);
}
return 1;
}
return undef;
};
my $acceptRegexMatch = sub
{
my ($picked_expr) = @_;
my $picked_expr_re;
eval { $picked_expr_re = qr/$picked_expr/p; };
if ( !$@ )
{
# compiled regex successfully
my $matched_any;
my %next_dupindex;
# I look through cols_all_legend_input instead of
# keys(%colindices_input) to preserve the original order
for my $matched_legend_input (@cols_all_legend_input)
{
$next_dupindex{$matched_legend_input} //= 0;
if ( $matched_legend_input =~ /$picked_expr_re/p && length(${^MATCH}) > 0 )
{
$accept->($matched_legend_input, undef,
$next_dupindex{$matched_legend_input});
$matched_any = 1;
$next_dupindex{$matched_legend_input}++;
}
}
return $matched_any;
}
return undef;
};
my $excludeExactMatch = sub
{
my ($expr) = @_;
my @picked_fields_filtered = grep {$_->[2] ne $expr} @picked_fields;
if( scalar(@picked_fields_filtered) == scalar(@picked_fields) )
{
return undef;
}
@picked_fields = @picked_fields_filtered;
return 1;
};
my $excludeRegexMatch = sub
{
my ($expr) = @_;
my $expr_re;
eval { $expr_re = qr/$expr/p; };
return undef if $@;
my @picked_fields_filtered = grep {! ($_->[2] =~ /$expr_re/p && length(${^MATCH})) } @picked_fields;
if( scalar(@picked_fields_filtered) == scalar(@picked_fields) )
{
return undef;
}
@picked_fields = @picked_fields_filtered;
return 1;
};
my $picked_expr_named = $picked_exprs_named[$i_picked_exprs_named];
next if $acceptExactMatch->($picked_expr_named, undef);
my ($name, $picked_expr) = $picked_expr_named =~ /(.*?)=(.*)/;
$picked_expr //= $picked_expr_named;
# No exact column match. If this is a named expression, I pass it on
# to awk/perl
if ( defined $name )
{
$accept->($picked_expr, $name);
next;
}
# No exact matches were found, and not a named expression. This
# is either a regex or an exclusion expression
if( $picked_expr =~ /^!(.*)/ )
{
# exclusion expression. I apply the same logic as before:
# try exact column matches first, and then a regex.
#
# I accumulate the picked list in order the arguments were
# given: each exclusion expression removes columns from the
# so-far-picked list. If the picked list BEGINS with an
# exclusion expression, we assume that ALL columns have been
# previously picked
#
# Here we match on the names of the OUTPUT columns
$picked_expr = $1;
if($i_picked_exprs_named == 0) { $acceptRegexMatch->('.'); }
next if $excludeExactMatch->($picked_expr);
next if $excludeRegexMatch->($picked_expr);
my @output_names_have = map {$_->[2]} @picked_fields;
die "Couldn't find requested column '$picked_expr' to exclude. Currently have output columns\n" . join('', map { " $_\n" } @output_names_have);
}
next if $acceptRegexMatch->($picked_expr);
die "Couldn't find requested column '$picked_expr'. Legend has the following columns:\n" . join('', map { " $_\n" } @cols_all_legend_input);
}
if(!@picked_fields)
{
die "After processing --pick options, no fields remain!";
}
for my $picked_field (@picked_fields)
{
my ($output_field, $colidx_needed_max_here, $colname_output) = @$picked_field;
push @colnames_output, $colname_output;
if ( $colidx_needed_max_here > $colidx_needed_max )
{
$colidx_needed_max = $colidx_needed_max_here;
}
push @langspecific_output_fields, $output_field;
}
}
else
{
# no columns requested. I take ALL the columns. I make sure to not
# explicitly look at any of the column names, so if we have
# duplicate columns, things will remain functional
@colnames_output = @cols_all_legend_input;
if( !$options{perl} )
{
@langspecific_output_fields = map { '$'. $_ } 1..(1+$#cols_all_legend_input);
}
else
{
@langspecific_output_fields = map { "\$fields[$_]" } 0..$#cols_all_legend_input;
}
}
# print out the new legend
unless($options{dumpexprs} || $options{eval})
{
print "# @colnames_output\n";
flush STDOUT if $options{unbuffered};
}
if( @must_have_col_names )
{
foreach my $col_name (@must_have_col_names)
{
# First I try exact matches for column names. Only unique
# matches accepted
if( defined $colindices_input{$col_name} )
{
if(1 == @{$colindices_input{$col_name}})
{
push @must_have_col_indices_input, $colindices_input{$col_name}[0];
next;
}
die "--has found multiple columns named '$col_name'; --has expects unique columns";
}
# No exact matches. Try regex matches. Again, only unique
# matches accepted
my $col_name_re;
eval { $col_name_re = qr/$col_name/p; };
if( $@ )
{
die "--has found no columns matching '$col_name'";
}
# compiled regex successfully
my $matching_col_index;
for my $matched_legend_input (keys(%colindices_input))
{
if ( $matched_legend_input =~ /$col_name_re/p && length(${^MATCH}) > 0 )
{
# Found match. Is it unique?
if(defined $matching_col_index || 1 != @{$colindices_input{$matched_legend_input}})
{
die "--has found multiple columns matching '$col_name'; --has expects unique columns";
}
# Found unique (for now) column
$matching_col_index = $colindices_input{$matched_legend_input}[0];
}
}
if(!defined $matching_col_index)
{
die "--has found no columns matching '$col_name'";
}
push @must_have_col_indices_input, $matching_col_index;
}
}
last;
}
die "Got data line before a legend";
}
if(!%colindices_input)
{
die "No legend received. Is the input file empty?";
}
# At this point I'm done dealing with the legend, and it's time to read in and
# process the data. I can keep going in perl, or I can generate an awk program,
# and let awk do this work. The reason: awk (mawk especialy) runs much faster.
# Both paths should produce the exact same output, and the test suite makes sure
# this is the case
if( !$options{perl} )
{
my $awkprogram = makeAwkProgram();
if( $options{dumpexprs} )
{
say $awkprogram;
exit;
}
if($options{unbuffered})
{
exec 'mawk', '-Winteractive', $awkprogram;
}
else
{
exec 'mawk', $awkprogram;
}
exit; # dummy. We never get here
}
sub makeAwkProgram
{
# The awk program I generate here is analogous to the logic in the data
# while() loop above
my $function_arguments = $options{function} // [];
if( $options{'function-abs'} )
{
push @$function_arguments, 'abs(___x___) { if(___x___ >= 0) { return ___x___;} return -___x___;}';
}
my $functions = join('', map { my ($sub) = expr_subst_col_names('awk', $_); "function $sub " } @$function_arguments);
my $awkprogram_preamble = '';
my $BEGIN = $options{begin} // '';
my $END = $options{end} // '';
if($any_context_stuff)
{
# context-handling stuff. This is a mirror of the perl implementation
# below. See the comments there for a description
$BEGIN .= ' ; ' .
'__i1_contextbuffer = 0; ' .
'__N_contextbuffer = 0; ' .
'__N_printafter = 0; ' .
'__just_skipped_something = 0; ' .
'__printed_something_ever = 0; ';
$awkprogram_preamble .= 'function __contextbuffer_output_and_clear() { ' .
"__i0_contextbuffer = __i1_contextbuffer - __N_contextbuffer; " .
"if(__i0_contextbuffer < 0){__i0_contextbuffer += $NcontextBefore;} " .
"while (__N_contextbuffer) { " .
" print __contextbuffer[__i0_contextbuffer++]; " .
" if(__i0_contextbuffer == $NcontextBefore){__i0_contextbuffer = 0} " .
" __N_contextbuffer--; " .
"} " .
"} ";
# pushes to the buffer. Returns TRUE if I did NOT just overwrite an element of
# the buffer
$awkprogram_preamble .= 'function __contextbuffer_push(__line) { ' .
'__contextbuffer[__i1_contextbuffer++] = __line; ' .
"if(__i1_contextbuffer == $NcontextBefore) {__i1_contextbuffer = 0} " .
"if(__N_contextbuffer != $NcontextBefore) {__N_contextbuffer++} " .
"} ";
}
$awkprogram_preamble = "BEGIN { $BEGIN } END { $END } $awkprogram_preamble";
# Deal with comments. If printing, these do not count towards the context
# stuff (-A/-B/-C)
$awkprogram_preamble .=
'/^ *(#|$)/ { ' . ($options{skipcomments} ? '' : 'print; ') . 'next } ';
# skip incomplete records. Can happen if a log line at the end of a file was
# cut off in the middle. These are invalid lines, so I don't even bother to
# handle -A/-B/-C
if( $colidx_needed_max >= 0)
{
$awkprogram_preamble .= (1+$colidx_needed_max) . " > NF { next } ";
}
# skip records that have empty input columns that must be non-empty
if (@must_have_col_indices_input)
{
$awkprogram_preamble .=
join(' || ', map { '$'.($_+1). " == \"-\"" } @must_have_col_indices_input);
$awkprogram_preamble .= " { next } ";
}
my $not_matches_condition = join(' || ',
map
{
my ($expr) = expr_subst_col_names('awk', $_);
'!' . "($expr)"
} @{$options{matches}});
my $awkprogram_matches = '';
my $awkprogram_print;
if($options{eval})
{
if( length($not_matches_condition) )
{
$awkprogram_matches .= $not_matches_condition . '{next}';
}
my ($expr) = expr_subst_col_names('awk', $options{eval});
$awkprogram_print .= "$expr ";
}
else
{
if( length($not_matches_condition) )
{
$awkprogram_matches .= $not_matches_condition . '{ ';
if ($any_context_stuff)
{
# get the line
$awkprogram_matches .= "__line = " . join('" "', @langspecific_output_fields) . "; ";
# save and skip the record
$awkprogram_matches .=
'if(__N_printafter) { ' .
' print __line; ' .
' __N_printafter--; ' .
'} ' .
"else { if(__N_contextbuffer == $NcontextBefore){__just_skipped_something = 1;} ";
if ($NcontextBefore)
{
$awkprogram_matches .= '__contextbuffer_push(__line); ';
}
$awkprogram_matches .= '} ';
}
$awkprogram_matches .= ' next } ';
}
# past if(!matches) {}
$awkprogram_print .= '{';
my $record_accept_pre_print = '';
my $record_accept_post_print = '';
if($any_context_stuff)
{
$record_accept_pre_print =
'if( __just_skipped_something && __printed_something_ever) { print "##" } ' .
'__just_skipped_something = 0; ' .
'__printed_something_ever = 1; ';
if($NcontextBefore)
{
$record_accept_pre_print .= '__contextbuffer_output_and_clear(); ';
}
####### now print the thing
$record_accept_post_print .=
"__N_printafter = $NcontextAfter; ";
}
# I evaluate the fields just one time to not affect the state inside
# rel() and diff(): I read them into local variables, and operate on
# those
#
# I make sure the reported field doesn't have length-0. This would
# confuse the vnlog fields
$awkprogram_print .=
join(' ',
map { "__f$_ = $langspecific_output_fields[$_]; if(length(__f$_)==0) { __f$_ = \"-\"; } " }
0..$#langspecific_output_fields);
if ($any_context_stuff)
{
$awkprogram_print .=
'__line = ' . join('" "', map {"__f$_"} 0..$#langspecific_output_fields) . '; ';
}
if ($options{skipempty})
{
$awkprogram_print .=
"if(" . join( ' && ', map { "__f$_ == \"-\""} 0..$#langspecific_output_fields ) .
") { next } ";
}
# And THEN I print everything
$awkprogram_print .=
$record_accept_pre_print .
'print ' . join(',', map {"__f$_"} 0..$#langspecific_output_fields) . '; ' .
$record_accept_post_print . ' ';
$awkprogram_print .= '}';
}
my $outer_expr = get_reldiff_outer_expr();
my $awkprogram_reldiff = '';
for my $i (0..$specialops{rel}{N}-1)
{
$awkprogram_reldiff .= "function rel$i(x) { if(!__inited_rel$i) { __state_rel$i = x; __inited_rel$i = 1; } return x - __state_rel$i; } ";
}
for my $i (0..$specialops{diff}{N}-1)
{
$awkprogram_reldiff .= "function diff$i(x) { retval = __inited_diff$i ? (x - __state_diff$i) : \"-\"; __state_diff$i = x; __inited_diff$i = 1; return retval; } ";
}
for my $i (0..$specialops{sum}{N}-1)
{
$awkprogram_reldiff .= "function sum$i(x) { __state_sum$i += x; return __state_sum$i; } ";
}
for my $i (0..$specialops{prev}{N}-1)
{
$awkprogram_reldiff .= "function prev$i(x) { __prev = length(__state_prev$i) ? __state_prev$i : \"-\"; __state_prev$i = x; return __prev; } ";
}
for my $i (0..$specialops{latestdefined}{N}-1)
{
$awkprogram_reldiff .= "function latestdefined$i(x) { if( x != \"-\" ) { __state_latestdefined$i = x; } return length(__state_latestdefined$i) ? __state_latestdefined$i : \"-\"; }";
}
my $awkprogram = $functions . $awkprogram_reldiff . $awkprogram_preamble;
if(length($outer_expr))
{
$awkprogram .= "{ $outer_expr } ";
}
$awkprogram .= $awkprogram_matches . $awkprogram_print;
return $awkprogram;
}
# line split(',', $s), but respects (). I.e. splitting "a,b,f(c,d)" produces 3
# tokens, not 4
sub split_on_comma_respect_parens
{
my ($s) = @_;
my @f;
FIELDS: # loop accumulating fields
while (1)
{
my $field_accum = '';
FIELD_ACCUM: # accumulate THIS field. Keep grabbing tokens until I see an
# , or the end
while(1)
{
if (length($s) == 0)
{
if (length($field_accum))
{
push @f, $field_accum;
}
last FIELDS;
}
if ($s !~ /^ # start of string
([^(,]*?) # some minimal number of non-comma, non-paren
([(,]) # comma or paren
/px) {
# didn't match. The whole thing is the last field
push @f, $field_accum . $s;
last FIELDS;
}
my ($pre,$sep) = ($1,$2);
if ($sep eq ',')
{
# we have a field
push @f, $field_accum . $pre;
$field_accum = '';
$s = ${^POSTMATCH};
next FIELD_ACCUM;
}
# we have a paren. accumulate
my ($paren_expr, $rest) = extract_bracketed($sep . ${^POSTMATCH}, '(');
if ( !defined $paren_expr )
{
# non-matched paren. Accum normally
$rest =~ /^\((.*)$/ or die "Weird... '$rest' should have started with a '('. Giving up";
$field_accum .= '(';
$s = $1;
next FIELD_ACCUM;
}
$field_accum .= $pre . $paren_expr;
$s = $rest;
}
}
return @f;
}
sub find_outer_specialop
{
# returns the FIRST outer specialop that appears in the given string, or
# undef if none are found
my ($str) = @_;
my $re_any = join('|', @all_specialops);
my $re = qr/^.*?\b($re_any)\s*\(/s;
$str =~ $re or return undef;
return $1;
}
sub subst_reldiff
{
# This is somewhat convoluted. I want the meaning of rel() and diff() and
# ... to be preserved regardless of any early-exit expressions. I.e. this
# sequence is broken:
#
# - if(!matches) { continue }
# - print rel() # update internal state
#
# because the internal state will not be updated if(!matches). I thus do
# this instead:
#
# - _rel = rel()
# - if(!matches) { continue }
# - print _rel
#
# This works. But to make it work, I need to pre-compute all the outermost
# rel() and diff() expressions. Outermost because rel(rel(x)) should still
# work properly. I thus do this:
#
# rel( rel(xxx) ) ------>
# function rel1() {} function rel2() {}
# __rel1 = rel1( rel2(xxx) ); ... __rel1
#
# I.e. each rel() gets a function defined with its own state. Only the
# outermost one is cached. This is done so that I evaluate all the rel()
# unconditionally, and then do conditional stuff (due to matches or
# skipempty)
my ($what, $expr, $isouter) = @_;
my $sigil = $options{perl} ? '$' : '';
my $N = \$specialops{$what}{N};
my $outer_list = $specialops{$what}{outer};
my $whatre = qr/\b$what\s*\(/p;
while( $expr =~ /$whatre/p )
{
if( !$isouter )
{
# not an outer one. Simply replace the call with a specific,
# numbered one
$expr =~ s/$whatre/$what$$N(/;
}
else
{
# IS an outer one. Replace the call with a variable that gets
# precomputed. Save the string for precomputation
my $prematch = ${^PREMATCH};
my ($paren_expr, $rest) = extract_bracketed("(${^POSTMATCH}", '[({');
if (!defined $paren_expr)
{
die "Giving up: Couldn't parse '$expr'";
}
$expr = $prematch . $sigil . "__$what$$N" . $rest;
push @$outer_list, [$$N, $paren_expr];
}
$$N++;
}
return $expr;
}
sub get_reldiff_outer_expr
{
# should be called AFTER all the outer rel/diff/... expressions were
# encountered. I.e. after the last expr_subst_col_names()
my $sigil = $options{perl} ? '$' : '';
my $expr = '';
for my $what (@all_specialops)
{
for my $e (@{$specialops{$what}{outer}})
{
my ($i, $paren_expr) = @$e;
# I keep substituting until I got everything. This is required
# because I can have deeply recursive calls
my $substituted = $paren_expr;
while(1)
{
my $start = $substituted;
for my $what_inner (@all_specialops)
{
$substituted = subst_reldiff($what_inner, $substituted, 0);
}
if($substituted eq $start) { last; }
}
$expr .= $sigil . "__$what$i = $what$i" . $substituted . '; ';
}
}
return $expr;
}
sub expr_subst_col_names
{
# I take in a string with awk/perl code, and replace field references to
# column references that the awk/perl program will understand. To minimize
# the risk of ambiguous matches, I try to match longer strings first
my ($language, $out, $dupindex) = @_;
# This looks odd. Mostly, $bound0 = $bound1 = '\b'. This would work to
# Find "normal" alphanumeric keys in the string. But my keys may have
# special characters in them. For instance, if I grab keys from the
# 'top' command, it'll produce a legend including keys '%CPU', 'TIME+',
# and the point before the '%' or after the '+' would not match \b. I
# thus expand the regex at the boundary. I match EITHER the normal \b
# meaning for a word-nonword transition OR a whitespace-nonword
# transition. This means that whitespace becomes important: '1+%CPU'
# will not be parsed as expected (but that's the RIGHT behavior here),
# but '1+ %CPU' will be parsed correctly
my $bound0 = '(?:(?<!\w)(?=\w)|(?:^|(?<=\s))(?!\w))';
my $bound1 = '(?:(?<=\w)(?!\w)|(?<!\w)(?:(?=\s)|$))';
my $keys = join('|', map( quotemeta, sort keys %colindices_input));
my $re = qr/$bound0(?:$keys)$bound1/;
my $colidx_needed_max_here = -1;
if ( $language eq 'awk' )
{
$out =~ s{$re}{
my $key = ${^MATCH};
if (!defined $dupindex && 1 != @{$colindices_input{$key}})
{
die "Asked to operate on key '$key', but this isn't unique";
}
my $colidx = $colindices_input{$key}[$dupindex // 0];
$colidx_needed_max_here = $colidx if $colidx_needed_max_here < $colidx;
# awk indexes from 1
$colidx++;
"\$$colidx";
}gep;
}
elsif ( $language eq 'perl' )
{
$out =~ s{$re}{
my $key = ${^MATCH};
if (!defined $dupindex && 1 != @{$colindices_input{$key}})
{
die "Asked to operate on key '$key', but this isn't unique";
}
my $colidx = $colindices_input{$key}[$dupindex // 0];
$colidx_needed_max_here = $colidx if $colidx_needed_max_here < $colidx;
"\$fields[$colidx]";
}gep;
}
else
{
die "Unknown language '$language";
}
while(my $what = find_outer_specialop($out))
{
$out = subst_reldiff ($what, $out, 1);
}
return ($out, $colidx_needed_max_here);
}
my $autoflushstr = $options{eval} && $options{unbuffered} ? '$| = 1; ' : '';
my $BEGIN = $options{begin} // '';
my $evalstr = $autoflushstr . $BEGIN . '; ' . join('', map { my ($sub) = expr_subst_col_names('perl', $_); "sub $sub\n"} @{$options{function}});
my $must_match_expr =
join ' && ',
map { my ($outexpr) = expr_subst_col_names( 'perl', $_); "( $outexpr )"; }
@{$options{matches}};
$must_match_expr = 1 if !defined $must_match_expr || '' eq $must_match_expr;