csvtool/Expr.pm

filter: Statementstmt 100% 11 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 100% 15 / 15 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« csvtool/Timetools.pm ↑ Summary
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2026 -- leonerd@leonerd.org.uk
5  
6 package App::csvtool::Expr 0.05;
7  
8 16 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 16 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 16 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 =head1 NAME
13  
14 C<App::csvtool::Expr> - F<csvtool> commands that evaluate expressions
15  
16 =head1 EXPRESSIONS
17  
18 =for highlighter
19  
20 Commands in this module operate on rows of data by evaluating expressions
21 given as part of the command's arguments. Expressions are built up from the
22 following forms:
23  
24 =over 4
25  
26 =item * Numerical constants
27  
28 Integers (e.g. C<123>) or decimal floats (e.g. C<12.345>)
29  
30 =item * Field references
31  
32 C<F[nnn]>, where the C<nnn> part gives the field index. Note that fields are
33 indexed from 1 onwards.
34  
35 =item * Parenthesized expressions
36  
37 Any expression may be surrounded by parens (C<( expr... )>) to override
38 precedence order
39  
40 =item * Numerical binary operators
41  
42 Mathematical operators (C<+ - * />) in their usual precedence order
43  
44 =item * Numerical comparison operators
45  
46 Numerical comparisons (C<< == != < <= >= > >>)
47  
48 =item * Logical binary operators
49  
50 Operators that compare the truth of expressions (C<&& ||>)
51  
52 =back
53  
54 =cut
55  
56 package App::csvtool::Expr::_Parser {
57 # This is a lot of special-case logic that is only loosely built on top
58 # of Parser::MGC; we're mostly using Parser::MGC as a tokenising lexer
59 # to base our own rule-based grammar parser on top of.
60 # However, it would be hard to migrate the underlying logic of this parser
61 # into Parser::MGC itself and manage to keep it sufficiently generic and
62 # powerful at the same time. We don't really want to turn it into a full
63 # grammar parser engine.
64 16 ▶ use base qw( Parser::MGC );
Subroutine BEGIN: called CC=1 SCAR=0.0
65  
66 my @binops = (
67 [qw( * / )],
68 [qw( + - )],
69 [qw( == != < <= >= > )],
70 [qw( && || )],
71 );
72  
73 my $op_pattern = join "|",
74 ( map { join "|", map { quotemeta } @$_ } @binops ),
75 ( map { quotemeta } qw[ ( ) ] );
76 $op_pattern = qr/$op_pattern/;
77  
78 sub _tail1 ( $x ) { [ @{$x}[1 .. $#$x] ] }
79  
80 my @rules = (
81 # (TERM) reduces to just TERM
82 [ '(', 'term', ')' ] => sub ( $, $term, $ ) { $term },
83 # binary operators in precedence order
84 ( map {
85 [ 'term', $_, 'term' ] =>
86 sub ( $lhs, $op, $rhs ) { [ term => binop => _tail1($lhs), @$op, _tail1($rhs) ] }
87 } @binops ),
88 );
89  
90 sub token ( $self )
91 {
92 return $self->any_of(
93 sub ( $self ) { [ term => const => $self->token_number ] },
94 sub ( $self ) { ( undef, my $index ) = $self->expect( qr/F\[(\d+)\]/ );
95 $index--; # because 1-based
96 [ term => expr => '$row->['.$index.']' ] },
97 sub ( $self ) { [ $self->expect( $op_pattern ) ] },
98 sub ( $self ) { $self->fail( "Expected term or operator" ) },
99 );
100 }
101  
102 sub parse ( $self )
103 {
104 my @stack = $self->token;
105  
106 while( !$self->at_eos ) {
107 my $next = $self->token;
108  
109 1 while @stack and $self->try_reduce( \@stack, $next );
110  
111 push @stack, $next;
112 }
113  
114 1 while @stack > 1 and $self->try_reduce( \@stack );
115 my $top = pop @stack;
116  
117 !@stack and $top->[0] eq "term" or
118 $self->fail( "Syntax error in expression" );
119  
120 return [ @{$top}[1..$#$top] ];
121 }
122  
123 sub _matches ( $top, $match )
124 {
125 return 0 unless @$top == @$match;
126 foreach my $i ( 0 .. $#$match ) {
127 my $got = $top->[$i][0];
128 my $want = $match->[$i];
129  
130 defined $got or next;
131  
132 my $ok = 0;
133  
134 if( ref $want eq "ARRAY" ) {
135 $got eq $_ and $ok = 1, last for @$want;
136 }
137 else {
138 $got eq $want and $ok = 1;
139 }
140  
141 $ok or return 0;
142 }
143  
144 return 1;
145 }
146  
147 sub try_reduce ( $self, $stack, $next = undef )
148 {
149 # Reduce the entire top of the stack, unless $next is defined and the
150 # addition of it might cause a higher-precedence rule to match
151 my $have_partial;
152 my $matchi;
153  
154 RULE: for ( my $i = 0; $i < @rules; $i += 2 ) {
155 my $match = $rules[$i];
156 my $len = @$match;
157  
158 if( @$stack >= $len ) {
159 my @top = @{$stack}[-$len .. -1];
160 $matchi = $i, last RULE
161 if _matches( \@top, $match );
162 }
163  
164 next RULE unless $next;
165  
166 foreach my $shortlen ( reverse 1 .. $len-1 ) {
167 next unless @$stack >= $shortlen;
168 my @top = ( @{$stack}[-$shortlen .. -1], $next, ( undef ) x ( $len - $shortlen - 1 ) );
169  
170 return 0
171 if _matches( \@top, $match );
172 }
173 }
174  
175 # If we fell off this list without $matchi that means the next item
176 # pushed to the stack cannot possibly ever match
177 defined $matchi or
178 $self->fail( "Syntax error in expression" );
179  
180 my $len = scalar @{$rules[$matchi]};
181 my $reducer = $rules[$matchi + 1];
182 my @top = splice @$stack, -$len, $len, ();
183  
184 push @$stack, $reducer->( @top );
185  
186 return 1;
187 }
188 }
189  
190 sub perl_code_for ( $pkg, $n )
191 {
192 my ( $type, @args ) = @$n;
193  
194 if( $type eq "expr" ) {
195 return $args[0];
196 }
197 if( $type eq "const" ) {
198 # TODO: perlish un-qq strings but for now we know these are just numbers
199 return "$args[0]";
200 }
201 if( $type eq "binop" ) {
202 my ( $lhs, $rhs ) = map { $pkg->perl_code_for( $_ ) } @args[0, 2];
203 my $op = $args[1];
204  
205 return "($lhs $op $rhs)";
206 }
207  
208 die "TODO: perl code for type=$type";
209 }
210  
211 sub compile ( $pkg, $expr )
212 {
213 my $n = App::csvtool::Expr::_Parser->new->from_string( $expr );
214 my $code = $pkg->perl_code_for( $n );
215  
216 # Silence numeric and uninitialized warnings during the filter code
217 my $sub = eval <<'EOF'
218 sub ( $row ) {
219 no warnings qw( numeric uninitialized );
220 EOF
221 . $code . '}' or
222 die "Cannot compile filter code: $@";
223 return $sub;
224 }
225  
226 =head1 COMMANDS
227  
228 =cut
229  
230 package App::csvtool::extend
231 {
232  
233 =head2 extend
234  
235 $ csvtool extend EXPR INPUT...
236  
237 Appends an extra column to each row, containing the result of the evaluated
238 expression on that row.
239  
240 =cut
241  
242 use constant COMMAND_DESC => "Evaluate an expression to append each row";
243  
244 use constant COMMAND_ARGS => (
245 { name => "expression", description => "expression to calculate" },
246 );
247  
248 use constant WANT_READER => 1;
249 use constant WANT_OUTPUT => 1;
250  
251 sub run ( $pkg, $expr, $reader, $output )
252 {
253 my $EXPR = App::csvtool::Expr->compile( $expr );
254  
255 while( my $row = $reader->() ) {
256 $output->( [ @$row, $EXPR->( $row ) ] );
257 }
258 }
259 }
260  
261 package App::csvtool::filter
262 {
263  
264 =head2 filter
265  
266 $ csvtool filter EXPR INPUT...
267  
268 Filter rows by the given expression, which is evaluated for each row. Rows for
269 which the expression is true are emitted unchanged; rows for which it is false
270 are skipped.
271  
272 =cut
273  
274 use constant COMMAND_DESC => "Filter rows by a given expression";
275  
276 use constant COMMAND_ARGS => (
277 { name => "expression", description => "expression to select rows" },
278 );
279  
280 use constant WANT_READER => 1;
281 use constant WANT_OUTPUT => 1;
282  
283 sub run ( $pkg, $expr, $reader, $output )
284 {
285 my $FILTER = App::csvtool::Expr->compile( $expr );
286  
287 while( my $row = $reader->() ) {
288 $output->( $row ) if $FILTER->( $row );
289 }
290 }
291 }
292  
293 =head1 TODO
294  
295 =over 4
296  
297 =item *
298  
299 Define many more operators. Functions. String operations. Allsorts...
300  
301 =back
302  
303 =head1 AUTHOR
304  
305 Paul Evans <leonerd@leonerd.org.uk>
306  
307 =cut
308  
309 0x55AA;
« csvtool/Timetools.pm ↑ Summary