blib/lib/Database/BI/Calc.pm

filter: Statementstmt 96.9% 596 / 615 Branchbran 93.8% 379 / 404 Conditioncond 90.1% 183 / 203 MC/DCmcdc 84.8% 95 / 112 Subroutinesub 96.1% 75 / 78 Podpod 50.0% 4 / 8 totaltotal 93.8% 1332 / 1420 CC 282 SCAR 24.6
CC
282
Cov
95%
_parse_call
45.3
__ANON__
28.1
_tokenize
18.0
CRAP 11.6
« script/database-bi ↑ Summary blib/lib/Database/BI/Summary.pm »
1 package Database::BI::Calc;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 2 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use POSIX qw(floor ceil);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Database::BI::I18N ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use Database::BI::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 our $VERSION = '0.023.1';
14  
15 2 Readonly my $MAX_EXPR_LEN => 512;
16 2 Readonly my $MAX_DEPTH => 20;
17  
18 # A double holds about 15 significant digits, so round() has nothing to say past
19 # that, and the count reaches sprintf from a URL: it must not be able to ask for
20 # two thousand million of them.
21 2 Readonly my $MAX_ROUND_PLACES => 15;
22  
23 # A pattern, and what one capture may hold. A capture becomes a group key, so an
24 # unbounded one is a performance and a layout problem; Perl's regex engine has no
25 # timeout, so the length cap is the only bound a pattern itself can be given.
26 2 Readonly my $MAX_PATTERN_LEN => 200;
27 2 Readonly my $MAX_CAPTURE_LEN => 200;
28  
29 # The constructs that run code or steer the engine: (?{ }) and (??{ }) run Perl,
30 # (?p is the old preserve flag, and (* opens a backtracking verb.
31 # A paren after an even number of backslashes is a real one, after an odd number
32 # a literal.
33 2 Readonly my $REFUSED_PATTERN_RE => qr/(?:\A|[^\\])(?:\\\\)*\K(\((?:\?\??\{|\?p|\*))/;
34  
35 # --- token type constants ---
36 2 Readonly my $T_NUM => 'NUM';
37 2 Readonly my $T_STR => 'STR';
38 2 Readonly my $T_IDENT => 'IDENT';
39 2 Readonly my $T_PLUS => 'PLUS';
40 2 Readonly my $T_MINUS => 'MINUS';
41 2 Readonly my $T_STAR => 'STAR';
42 2 Readonly my $T_SLASH => 'SLASH';
43 2 Readonly my $T_LPAREN => 'LPAREN';
44 2 Readonly my $T_RPAREN => 'RPAREN';
45 2 Readonly my $T_COMMA => 'COMMA';
46 2 Readonly my $T_EOF => 'EOF';
47  
48 # Comparison operator tokens (two-char forms checked before single-char forms)
49 2 Readonly my $T_EQ => 'EQ'; # =
50 2 Readonly my $T_NEQ => 'NEQ'; # !=
51 2 Readonly my $T_LT => 'LT'; # <
52 2 Readonly my $T_LE => 'LE'; # <=
53 2 Readonly my $T_GT => 'GT'; # >
54 2 Readonly my $T_GE => 'GE'; # >=
55  
56 2 our %MESSAGES = (
57 error_expr_too_long => 'Expression too long (max %d characters)',
58 error_expr_too_deep => 'Expression nesting too deep (max %d levels)',
59 error_unknown_fn => "Unknown function '%s'",
60 error_unknown_col => "Unknown column '%s'",
61 error_unexpected_tok => "Unexpected token '%s' at position %d",
62 error_expected_tok => "Expected '%s' at position %d, got '%s'",
63 error_unterminated => 'Unterminated string at position %d',
64 error_bad_char => "Unexpected character '%s' at position %d",
65 error_trailing => "Unexpected token '%s' at position %d",
66 error_double_eq => "Use = not == for equality comparison at position %d",
67 error_param_col_clash => "Parameter '%s' conflicts with a column of the same name",
68 error_time_format => "Unsupported time format token %s",
69 error_time_format_date => "Time format '%s' must name a date, with a year, a month and a day token",
70 error_const_arg => "The second argument of %s() must be a quoted literal",
71 error_span_interval => "Unknown time bucket '%s'; use a count and one of s, m, h, d, w, mon, q or y, for example 1h or 15m",
72 error_pattern_too_long => "Pattern '%s' is longer than %d characters",
73 error_pattern_construct => "Pattern '%s' uses %s, which is not allowed",
74 error_pattern_invalid => "Pattern '%s' does not compile: %s",
75 error_rx_args => 'rx() takes a column, a quoted pattern and an optional quoted group',
76 );
77  
78 106 ▶sub _fmt {
Subroutine _fmt: called CC=1 SCAR=0.0
79 106 my ($key, @args) = @_;
80 106 return sprintf Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key), @args;
81 }
82  
83 # --- built-in function dispatch table ---
84 # 'if' is handled as a special form in _parse_call (short-circuit branches),
85 # and so are epoch() and span(), whose second argument is a constant that is
86 # checked once, at compile time, rather than on every row.
87 #
88 # The date functions accept an ISO-8601 'YYYY-MM-DD' prefix only, and the time
89 # functions an ISO date, an ISO timestamp, or an epoch in seconds or
90 # milliseconds; non-matching values return undef and appear in the empty-cell
91 # bucket rather than being dropped.
92  
93 2 Readonly my %_MONTH_NAME_TO_NUM => (
94 jan => 1, feb => 2, mar => 3, apr => 4, may => 5, jun => 6,
95 jul => 7, aug => 8, sep => 9, oct => 10, nov => 11, dec => 12,
96 );
97  
98 # The tokens a strptime-style pattern may hold. Plain characters in a pattern
99 # are literals; anything else is a compile error, so a pattern is either fully
100 # understood or refused.
101 2 Readonly my %_FMT_RE => (
102 Y => '\d{4}', # four-digit year
103 m => '\d{1,2}', # month number
104 d => '\d{1,2}', # day of month
105 H => '\d{1,2}', # hour, 24-hour clock
106 M => '\d{1,2}', # minute
107 S => '\d{1,2}', # second
108 b => '[A-Za-z]{3}', # month abbreviation, as in %d-%b-%Y
109 );
110  
111 # The functions whose second argument is a constant, not an expression.
112 2 Readonly my %TIME_CONST_FNS => map { $_ => 1 } qw(epoch span);
113  
114 my %FUNCTIONS = (
115 # --- string functions ---
116 3 ▶ upper => sub { defined $_[0] ? uc($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 1 3
117 3 ▶ lower => sub { defined $_[0] ? lc($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 1 3
118 3 ▶ trim => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
119 3 ▶ return undef unless defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 1 2 3
120 2 my $s = $_[0];
121 2 $s =~ s/\A\s+|\s+\z//g;
122 2 $s;
123 },
124 3 ▶ len => sub { defined $_[0] ? length($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 1 3
125 4 ▶ concat => sub { join '', map { defined $_ ? $_ : '' } @_ },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 8 1 9
126 8 ▶ substr => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
127 8 my ($s, $start, $len) = @_;
128 8 ▶ return undef unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 1 7 8
129 7 ▶ $start //= 0;
Condition50%1/2
$start //= 0
l!l
70
MC/DC0%0/1
$start //= 0
$start
Truth table50%1/2
A
A= $start
Aresult
11
00
130 # A start past the end is undef, the empty-cell result; it is not worth one
131 # log line per row.
132 2 ▶ no warnings 'substr';
Subroutine BEGIN: called CC=1 SCAR=0.0
133 7 ▶ defined $len ? CORE::substr($s, $start, $len)
Branch: 1 branch
BranchTrueFalseTotal
defined $len ? : 4 3 7
134 : CORE::substr($s, $start);
135 },
136  
137 # --- numeric functions ---
138 11 ▶ round => sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
139 11 my ($n, $d) = @_;
140 11 ▶ return undef unless defined $n && looks_like_number($n);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and &looks_like_number($n) 2 9 11
Condition100%3/3
defined $n and &looks_like_number($n)
!ll&&!rl&&r
119
MC/DC100%2/2
defined $n and &looks_like_number($n)
defined $n &looks_like_number($n)
Truth table100%3/3
A and B
A= defined $nB= &looks_like_number($n)
ABresult
0X0
100
111
141 9 ▶ $d = (defined $d && looks_like_number($d)) ? int($d) : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $d && &looks_like_number($d) ? : 6 3 9
Condition100%3/3
defined $d and &looks_like_number($d)
!ll&&!rl&&r
216
MC/DC100%2/2
defined $d and &looks_like_number($d)
defined $d &looks_like_number($d)
Truth table100%3/3
A and B
A= defined $dB= &looks_like_number($d)
ABresult
0X0
100
111
142 9 ▶ $d = $MAX_ROUND_PLACES if $d > $MAX_ROUND_PLACES;
Branch: 1 branch
BranchTrueFalseTotal
if $d > $MAX_ROUND_PLACES 1 8 9
143 9 ▶ $d = -$MAX_ROUND_PLACES if $d < -$MAX_ROUND_PLACES;
Branch: 1 branch
BranchTrueFalseTotal
if $d < -$MAX_ROUND_PLACES 1 8 9
144 9 ▶ return sprintf("%.${d}f", $n) + 0 if $d >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $d >= 0 6 3 9
145  
146 # Negative places round to the left of the point: round(1234, -2) is 1200.
147 3 my $unit = 10 ** -$d;
148 3 sprintf('%.0f', $n / $unit) * $unit;
149 },
150 5 ▶ floor => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
151 5 ▶ defined $_[0] && looks_like_number($_[0]) ? POSIX::floor($_[0]) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && &looks_like_number($_[0]) ? : 3 2 5
Condition100%3/3
defined $_[0] and &looks_like_number($_[0])
!ll&&!rl&&r
113
MC/DC100%2/2
defined $_[0] and &looks_like_number($_[0])
defined $_[0] &looks_like_number($_[0])
Truth table100%3/3
A and B
A= defined $_[0]B= &looks_like_number($_[0])
ABresult
0X0
100
111
152 },
153 3 ▶ ceil => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
154 3 ▶ defined $_[0] && looks_like_number($_[0]) ? POSIX::ceil($_[0]) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && &looks_like_number($_[0]) ? : 2 1 3
Condition66%2/3
defined $_[0] and &looks_like_number($_[0])
!ll&&!rl&&r
012
MC/DC50%1/2
defined $_[0] and &looks_like_number($_[0])
defined $_[0] &looks_like_number($_[0])
Truth table66%2/3
A and B
A= defined $_[0]B= &looks_like_number($_[0])
ABresult
0X0
100
111
155 },
156 4 ▶ 'abs' => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
157 4 ▶ defined $_[0] && looks_like_number($_[0]) ? CORE::abs($_[0]) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && &looks_like_number($_[0]) ? : 3 1 4
Condition66%2/3
defined $_[0] and &looks_like_number($_[0])
!ll&&!rl&&r
013
MC/DC50%1/2
defined $_[0] and &looks_like_number($_[0])
defined $_[0] &looks_like_number($_[0])
Truth table66%2/3
A and B
A= defined $_[0]B= &looks_like_number($_[0])
ABresult
0X0
100
111
158 },
159  
160 # --- conditional / null-handling ---
161 4 ▶ isnull => sub { defined $_[0] ? $_[0] : $_[1] },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 2 4
162 6 ▶ coalesce => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
163 6 ▶ for my $v (@_) { return $v if defined $v }
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 4 6 10
164 2 return undef;
165 },
166  
167 # --- date functions (ISO-8601 YYYY-MM-DD prefix; no external module) ---
168 5 ▶ year => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
169 5 ▶ return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-\d\d-\d\d/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A(\d{4})-\d\d-\d\d/ 3 2 5
Condition100%3/3
defined $_[0] and $_[0] =~ /\A(\d{4})-\d\d-\d\d/
!ll&&!rl&&r
122
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A(\d{4})-\d\d-\d\d/
defined $_[0] $_[0] =~ /\A(\d{4})-\d\d-\d\d/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A(\d{4})-\d\d-\d\d/
ABresult
0X0
100
111
170 2 $1 + 0;
171 },
172 7 ▶ month => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
173 7 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/ 5 2 7
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
!ll&&!rl&&r
142
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
defined $_[0] $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
ABresult
0X0
100
111
174 2 $1 + 0;
175 },
176 6 ▶ day => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
177 6 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/ 4 2 6
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
!ll&&!rl&&r
132
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
defined $_[0] $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
ABresult
0X0
100
111
178 2 $1 + 0;
179 },
180 8 ▶ quarter => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
181 8 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/ 4 4 8
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
!ll&&!rl&&r
134
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
defined $_[0] $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
ABresult
0X0
100
111
182 4 int(($1 - 1) / 3) + 1;
183 },
184 6 ▶ week => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
185 # Returns ISO 8601 week number (1-53); week containing the first
186 # Thursday of the year is week 1.
187 6 ▶ return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/ 2 4 6
Condition100%3/3
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
!ll&&!rl&&r
114
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
defined $_[0] $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
ABresult
0X0
100
111
188 4 my $t = _epoch_of($1 + 0, $2 + 0, $3 + 0, 12, 0, 0);
189 4 ▶ return undef unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 2 2 4
190 2 my @lt = localtime($t);
191 # Not strftime('%V'): the Windows C runtime does not have it, and
192 # gives ''.
193 2 _iso_week($lt[5] + 1900, $lt[6], $lt[7]);
194 },
195 6 ▶ month_name => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
196 # Returns full English month name, e.g. 'January'.
197 6 my @M = qw(January February March April May June
198 July August September October November December);
199 6 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/ 4 2 6
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
!ll&&!rl&&r
132
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
defined $_[0] $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
ABresult
0X0
100
111
200 2 $M[$1 - 1];
201 },
202 8 ▶ weekday => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
203 # Returns ISO 8601 weekday: 1 = Monday, 7 = Sunday.
204 8 ▶ return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/ 2 6 8
Condition100%3/3
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
!ll&&!rl&&r
116
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
defined $_[0] $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
ABresult
0X0
100
111
205 6 my $t = _epoch_of($1 + 0, $2 + 0, $3 + 0, 12, 0, 0);
206 6 ▶ return undef unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 2 4 6
207 4 my $wd = (localtime($t))[6]; # 0 = Sunday
208 4 ▶ $wd == 0 ? 7 : $wd;
Branch: 1 branch
BranchTrueFalseTotal
$wd == 0 ? : 2 2 4
209 },
210 2 ▶ now => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
211 # Returns today's date as 'YYYY-MM-DD'. Takes no arguments.
212 2 my @t = (localtime)[3, 4, 5]; # mday, mon (0-based), year (since 1900)
213 2 sprintf '%04d-%02d-%02d', $t[2] + 1900, $t[1] + 1, $t[0];
214 },
215  
216 # --- time of day (see "Time values and time buckets" below) --
217 4 ▶ hour => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
218 4 my $t = _parse_time($_[0]);
219 4 ▶ return undef unless $t && $t->{has_time};
Branch: 1 branch
BranchTrueFalseTotal
unless $t and $t->{"has_time"} 3 1 4
Condition100%3/3
$t and $t->{"has_time"}
!ll&&!rl&&r
211
MC/DC100%2/2
$t and $t->{"has_time"}
$t $t->{"has_time"}
Truth table100%3/3
A and B
A= $tB= $t->{"has_time"}
ABresult
0X0
100
111
220 1 (localtime($t->{epoch}))[2] + 0;
221 },
222 3 ▶ minute => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
223 3 my $t = _parse_time($_[0]);
224 3 ▶ return undef unless $t && $t->{has_time};
Branch: 1 branch
BranchTrueFalseTotal
unless $t and $t->{"has_time"} 2 1 3
Condition66%2/3
$t and $t->{"has_time"}
!ll&&!rl&&r
201
MC/DC50%1/2
$t and $t->{"has_time"}
$t $t->{"has_time"}
Truth table66%2/3
A and B
A= $tB= $t->{"has_time"}
ABresult
0X0
100
111
225 1 (localtime($t->{epoch}))[1] + 0;
226 },
227 3 ▶ second => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
228 3 my $t = _parse_time($_[0]);
229 3 ▶ return undef unless $t && $t->{has_time};
Branch: 1 branch
BranchTrueFalseTotal
unless $t and $t->{"has_time"} 2 1 3
Condition66%2/3
$t and $t->{"has_time"}
!ll&&!rl&&r
201
MC/DC50%1/2
$t and $t->{"has_time"}
$t $t->{"has_time"}
Truth table66%2/3
A and B
A= $tB= $t->{"has_time"}
ABresult
0X0
100
111
230 1 (localtime($t->{epoch}))[0] + 0;
231 },
232  
233 # --- grouping / binning ---
234 24 ▶ bin => sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
235 # bin(value, width) -> '[lo,hi)' label for the interval containing value.
236 # Width must be a positive number. Both endpoints use %d when width is
237 # an integer, %g otherwise, to avoid spurious ".0" suffixes.
238 24 my ($v, $w) = @_;
239 24 ▶ return undef unless defined $v && defined $w;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and defined $w 2 22 24
Condition100%3/3
defined $v and defined $w
!ll&&!rl&&r
1122
MC/DC100%2/2
defined $v and defined $w
defined $v defined $w
Truth table100%3/3
A and B
A= defined $vB= defined $w
ABresult
0X0
100
111
240 22 ▶ return undef unless looks_like_number($v) && looks_like_number($w) && $w > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($v) and &looks_like_number($w) and $w > 0 6 16 22
Condition100%6/6
&looks_like_number($v) and &looks_like_number($w) and $w > 0
!ll&&!rl&&r
2416
&looks_like_number($v) and &looks_like_number($w)
!ll&&!rl&&r
1120
MC/DC100%3/3
&looks_like_number($v) and &looks_like_number($w) and $w > 0
&looks_like_number($v) &looks_like_number($w) $w > 0
Truth table100%4/4
A and B and C
A= &looks_like_number($v)B= &looks_like_number($w)C= $w > 0
ABCresult
0XX0
10X0
1100
1111
241 # Normalise the quotient to 10 significant digits before flooring: binary
242 # representation error (0.3 / 0.1 == 2.9999999999999996) must not move a
243 # value one bin to the left. %.10g is magnitude-independent.
244 16 my $n = POSIX::floor(sprintf('%.10g', $v / $w) + 0);
245 16 my $lo = $n * $w;
246 16 my $hi = $lo + $w;
247 16 ▶ my $fmt = ($w == int($w)) ? '%d' : '%g';
Branch: 1 branch
BranchTrueFalseTotal
$w == int $w ? : 8 8 16
248 16 sprintf("[${fmt},${fmt})", $lo, $hi);
249 },
250 2 );
251  
252 # ---------------------------------------------------------------------------
253 # Time values and time buckets
254 #
255 # One parser and one interval vocabulary, with the time-of-day functions and
256 # span() on top of them. Every value is read as *local* time, by
257 # POSIX::mktime, exactly as the date functions and the relative time ranges
258 # already are: no zone is parsed, none is stored, and nothing here reads the
259 # clock -- a bucket for a value is the same bucket tomorrow.
260 # ---------------------------------------------------------------------------
261  
262 # _fmt_body($fmt) -> ($regex_body, \@tokens)
263 #
264 # Purpose: Turn a strptime-style pattern into a regex body with one capture per
265 # token, plus the token each capture belongs to. A token outside
266 # %_FMT_RE is a compile error rather than a silent skip: a pattern
267 # that quietly ignored half of itself is how a value ends up in the
268 # wrong bucket without anybody being told.
269 36 ▶sub _fmt_body {
Subroutine _fmt_body: called CC=8 SCAR=20.8
270 36 my ($fmt) = @_;
271 36 my @tokens;
272 36 my $body = '';
273 36 my $i = 0;
274  
275 36 ▶ while ($i < length $fmt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < length $fmt) 129 28 157
276 129 my $ch = substr($fmt, $i, 1);
277 129 ▶ if ($ch ne '%') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch ne "%") 57 72 129
278 57 $body .= quotemeta($ch);
279 57 $i++;
280 57 next;
281 }
282 72 my $tok = substr($fmt, $i + 1, 1);
283 croak _fmt('error_time_format', length($tok // '') ? "%$tok" : $fmt)
284 72 ▶ unless length($tok // '') && exists $_FMT_RE{$tok};
Branch: 2 branches
BranchTrueFalseTotal
unless length($tok // "") and exists $_FMT_RE{$tok} 8 64 72
length($tok // '') ? : 7 1 8
Condition71%5/7
length($tok // "") and exists $_FMT_RE{$tok}
!ll&&!rl&&r
1764
$tok // ""
l!l
720
$tok // ""
l!l
80
MC/DC50%1/2
length($tok // "") and exists $_FMT_RE{$tok}
$tok exists $_FMT_RE{$tok}
Truth table66%2/3
A and B
A= $tokB= exists $_FMT_RE{$tok}
ABresult
0X0
100
111
285 64 push @tokens, $tok;
286 64 $body .= '(' . $_FMT_RE{$tok} . ')';
287 64 $i += 2;
288 }
289  
290 28 return ($body, \@tokens);
291 }
292  
293 # _fmt_compile($fmt) -> { re => qr, tokens => \@tokens }
294 #
295 # A pattern on its own has to name a date; a time with no day has no place on a
296 # calendar to be resolved against.
297 15 ▶sub _fmt_compile {
Subroutine _fmt_compile: called CC=2 SCAR=6.9
298 15 my ($fmt) = @_;
299 15 my ($body, $tokens) = _fmt_body($fmt);
300 12 ▶ croak _fmt('error_time_format_date', $fmt)
Branch: 1 branch
BranchTrueFalseTotal
unless _fmt_has_date($tokens) 2 10 12
301 unless _fmt_has_date($tokens);
302 10 return { re => qr/\A$body\z/, tokens => $tokens };
303 }
304  
305 # _fmt_has_date(\@tokens) -> bool
306 #
307 # A pattern has to name a date: a year, a day, and a month -- as a number
308 # (C<%m>) or as an abbreviation (C<%b>), which is what %d-%b-%Y uses.
309 23 ▶sub _fmt_has_date {
Subroutine _fmt_has_date: called CC=5 SCAR=16.1
310 23 my ($tokens) = @_;
311 23 my %has = map { $_ => 1 } @$tokens;
312 23 ▶ return $has{Y} && $has{d} && ($has{m} || $has{b}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$has{'Y'} && $has{'d'} && ($has{'m'} || $has{'b'}) ? : 16 7 23
Condition100%9/9
$has{"Y"} and $has{"d"} and $has{"m"} || $has{"b"}
!ll&&!rl&&r
6116
$has{"Y"} and $has{"d"}
!ll&&!rl&&r
5117
$has{"m"} or $has{"b"}
l!l&&r!l&&!r
1421
MC/DC100%4/4
$has{"Y"} and $has{"d"} and $has{"m"} || $has{"b"}
$has{"Y"} $has{"d"} $has{"m"} $has{"b"}
Truth table100%5/5
A and B and C or D
A= $has{"Y"}B= $has{"d"}C= $has{"m"}D= $has{"b"}
ABCDresult
0XXX0
10XX0
11000
111X1
11011
313 }
314  
315 # _fmt_compile_pair($date_fmt, $time_fmt) -> { re => qr, tokens => \@tokens }
316 #
317 # A stored time pattern is two patterns holding one value between them, so they
318 # are compiled into one regex: the date, an optional 'T' or space, the time.
319 7 ▶sub _fmt_compile_pair {
Subroutine _fmt_compile_pair: called CC=2 SCAR=6.9
320 7 my ($date_fmt, $time_fmt) = @_;
321 7 my ($dbody, $dtokens) = _fmt_body($date_fmt);
322 7 my ($tbody, $ttokens) = _fmt_body($time_fmt);
323 5 ▶ croak _fmt('error_time_format_date', $date_fmt)
Branch: 1 branch
BranchTrueFalseTotal
unless _fmt_has_date($dtokens) 1 4 5
324 unless _fmt_has_date($dtokens);
325 return {
326 4 re => qr/\A$dbody[ T]?$tbody\z/,
327 tokens => [ @$dtokens, @$ttokens ],
328 };
329 }
330  
331 # _fmt_parts($value, $compiled) -> \%parts | undef
332 17 ▶sub _fmt_parts {
Subroutine _fmt_parts: called CC=3 SCAR=11.0
333 17 my ($value, $compiled) = @_;
334 17 my @caps = ($value =~ $compiled->{re});
335 17 ▶ return undef unless @caps;
Branch: 1 branch
BranchTrueFalseTotal
unless @caps 4 13 17
336  
337 13 my %part;
338 13 my @tokens = @{ $compiled->{tokens} };
339 13 for my $i (0 .. $#tokens) {
340 43 $part{ $tokens[$i] } = $caps[$i];
341 }
342 13 return \%part;
343 }
344  
345 # _epoch_of($y, $mon, $day, $h, $mi, $s) -> epoch | undef
346 #
347 # Purpose: Local epoch seconds for a calendar date and clock time.
348 # Notes: POSIX::mktime normalises what it is given -- '2026-02-31' becomes
349 # 3 March, month 13 becomes January -- so the parts are read back and
350 # compared before the value is accepted, and a date that does not
351 # exist is unparseable rather than quietly a different date. The
352 # clock time is allowed two hours of slack, because the hour a
353 # daylight-saving change skips does not exist and mktime moves it.
354 # _iso_week($year, $wday, $yday) -> 1..53
355 #
356 # The ISO 8601 week of a day, from localtime's weekday (0 = Sunday) and day of
357 # the year (0 = 1 January). Week 1 holds the year's first Thursday, so the
358 # first days of January can be in the last week of the year before, and the
359 # last days of December in week 1 of the next.
360 450 ▶sub _iso_week {
Subroutine _iso_week: called CC=5 SCAR=16.1
361 450 my ($year, $wday, $yday) = @_;
362 450 ▶ my $leap = sub { my $y = shift; ($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0 };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
$y % 4 == 0 and $y % 100 != 0 or $y % 400 == 0 89 319 408
Condition100%3/3
$y % 4 == 0 and $y % 100 != 0
!ll&&!rl&&r
3071289
MC/DC100%2/2
$y % 4 == 0 and $y % 100 != 0
$y % 4 == 0 $y % 100 != 0
Truth table100%3/3
A and B
A= $y % 4 == 0B= $y % 100 != 0
ABresult
0X0
100
111
363 # Monday is 1 and Sunday 7, as ISO counts.
364 450 ▶ my $iso_wday = $wday || 7;
Condition100%2/2
$wday || 7
l!l
38664
MC/DC100%1/1
$wday || 7
$wday
Truth table100%2/2
A
A= $wday
Aresult
11
00
365 450 my $week = int(($yday + 1 - $iso_wday + 10) / 7);
366 # The weekday of 1 January, 0 = Sunday.
367 450 my $jan1 = ($wday - $yday) % 7;
368 450 ▶ my $weeks = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
369 450 my ($y, $j1) = @_;
370 450 ▶ return ($j1 == 4 || ($leap->($y) && $j1 == 3)) ? 53 : 52;
Branch: 1 branch
BranchTrueFalseTotal
$j1 == 4 || &$leap($y) && $j1 == 3 ? : 89 361 450
Condition100%6/6
$j1 == 4 or &$leap($y) and $j1 == 3
l!l&&r!l&&!r
7118361
&$leap($y) and $j1 == 3
!ll&&!rl&&r
2847718
MC/DC100%3/3
$j1 == 4 or &$leap($y) and $j1 == 3
$j1 == 4 &$leap($y) $j1 == 3
Truth table100%4/4
A or B and C
A= $j1 == 4B= &$leap($y)C= $j1 == 3
ABCresult
1XX1
0111
00X0
0100
371 450 };
372 450 ▶ if ($week < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($week < 1) 29 421 450
373 29 ▶ my $prev_jan1 = ($jan1 - ($leap->($year - 1) ? 366 : 365)) % 7;
Branch: 1 branch
BranchTrueFalseTotal
&$leap($year - 1) ? : 6 23 29
374 29 return $weeks->($year - 1, $prev_jan1);
375 }
376 421 ▶ return 1 if $week > $weeks->($year, $jan1);
Branch: 1 branch
BranchTrueFalseTotal
if $week > &$weeks($year, $jan1) 27 394 421
377 394 return $week;
378 }
379  
380 97 ▶sub _epoch_of {
Subroutine _epoch_of: called CC=6 SCAR=18.0
381 97 my ($y, $mon, $day, $h, $mi, $s) = @_;
382 # mktime and localtime run the C library's tzset, which on FreeBSD can
383 # leave errno set (EILSEQ) when it succeeds: the caller's $! is kept.
384 97 local $!;
385 97 require POSIX;
386 97 my $epoch = POSIX::mktime($s, $mi, $h, $day, $mon - 1, $y - 1900);
387 97 ▶ return undef unless defined $epoch;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $epoch 0 97 97
388  
389 97 my @lt = localtime($epoch);
390 return undef
391 97 ▶ unless $lt[5] + 1900 == $y && $lt[4] + 1 == $mon && $lt[3] == $day;
Branch: 1 branch
BranchTrueFalseTotal
unless $lt[5] + 1900 == $y and $lt[4] + 1 == $mon and $lt[3] == $day 28 69 97
Condition100%6/6
$lt[5] + 1900 == $y and $lt[4] + 1 == $mon and $lt[3] == $day
!ll&&!rl&&r
26269
$lt[5] + 1900 == $y and $lt[4] + 1 == $mon
!ll&&!rl&&r
131371
MC/DC100%3/3
$lt[5] + 1900 == $y and $lt[4] + 1 == $mon and $lt[3] == $day
$lt[5] + 1900 == $y $lt[4] + 1 == $mon $lt[3] == $day
Truth table100%4/4
A and B and C
A= $lt[5] + 1900 == $yB= $lt[4] + 1 == $monC= $lt[3] == $day
ABCresult
0XX0
10X0
1100
1111
392  
393 69 my $want = $h * 3_600 + $mi * 60 + $s;
394 69 my $got = $lt[2] * 3_600 + $lt[1] * 60 + $lt[0];
395 69 ▶ return undef if abs($got - $want) > 7_200;
Branch: 1 branch
BranchTrueFalseTotal
if abs $got - $want > 7200 0 69 69
396 69 return $epoch;
397 }
398  
399 # _parse_time($value) -> { epoch => E, has_time => 0|1 } | undef
400 #
401 # Purpose: Read one cell as a point in time. Three shapes are recognised, in
402 # this order: an ISO date, or an ISO timestamp with 'T' or a space
403 # between the date and the time (a fraction of a second and a zone
404 # are accepted and not applied: Database::BI::Util::iso_datetime);
405 # ten digits, an epoch in seconds; and
406 # thirteen digits, an epoch in milliseconds. Only the digit count
407 # separates the last two, so it is the rule -- and it is documented,
408 # because nothing in the value itself says which one it is.
409 64 ▶sub _parse_time {
Subroutine _parse_time: called CC=13 SCAR=25.6
410 64 my ($value) = @_;
411 64 ▶ return undef unless defined $value && !ref $value && length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and length $value 8 56 64
Condition100%6/6
defined $value and not ref $value and length $value
!ll&&!rl&&r
6256
defined $value and not ref $value
!ll&&!rl&&r
5158
MC/DC100%3/3
defined $value and not ref $value and length $value
defined $value not ref $value length $value
Truth table100%4/4
A and not(B) and C
A= defined $valueB= not ref $valueC= length $value
ABCresult
0XX0
10X0
1100
1111
412 56 (my $s = $value) =~ s/\A\s+|\s+\z//g;
413 56 ▶ return undef unless length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless length $s 1 55 56
414  
415 55 my ($ymd, $h, $mi, $sec) = Database::BI::Util::iso_datetime($s);
416 55 ▶ if (defined $ymd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ymd) 40 15 55
417 40 my ($y, $mon, $day) = split /-/, $ymd;
418 40 ▶ my $epoch = _epoch_of($y + 0, $mon + 0, $day + 0,
Condition100%6/6
$h // 0
l!l
1030
$mi // 0
l!l
1030
$sec // 0
l!l
832
MC/DC100%1/1
$h // 0
$h
MC/DC100%1/1
$mi // 0
$mi
MC/DC100%1/1
$sec // 0
$sec
Truth table100%2/2
A
A= $h
Aresult
11
00
Truth table100%2/2
A
A= $mi
Aresult
11
00
Truth table100%2/2
A
A= $sec
Aresult
11
00
419 ($h // 0) + 0, ($mi // 0) + 0, ($sec // 0) + 0);
420 40 ▶ return undef unless defined $epoch;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $epoch 4 36 40
421 36 ▶ return { epoch => $epoch, has_time => defined $h ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
defined $h ? : 9 27 36
422 }
423  
424 15 ▶ return { epoch => $s + 0, has_time => 1 } if $s =~ /\A\d{10}\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\d{10}\z/ 1 14 15
425 14 ▶ return { epoch => int($s / 1_000), has_time => 1 } if $s =~ /\A\d{13}\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\d{13}\z/ 1 13 14
426 13 return undef;
427 }
428  
429 # _time_from_format($value, $compiled) -> { epoch => E, has_time => 0|1 } | undef
430 17 ▶sub _time_from_format {
Subroutine _time_from_format: called CC=14 SCAR=26.4
431 17 my ($value, $compiled) = @_;
432 17 ▶ return undef unless defined $value && !ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value 2 15 17
Condition100%3/3
defined $value and not ref $value
!ll&&!rl&&r
1115
MC/DC100%2/2
defined $value and not ref $value
defined $value not ref $value
Truth table100%3/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
433 15 ▶ my $part = _fmt_parts($value, $compiled) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $part = _fmt_parts($value, $compiled) or return undef 12 3 15
434  
435 my $mon = defined $part->{m} ? $part->{m} + 0
436 : defined $part->{b} ? $_MONTH_NAME_TO_NUM{ lc $part->{b} }
437 12 ▶ : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $part->{'m'} ? : 8 4 12
defined $part->{'b'} ? : 4 0 4
438 12 ▶ return undef unless defined $mon && $mon >= 1 && $mon <= 12;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mon and $mon >= 1 and $mon <= 12 3 9 12
Condition100%6/6
defined $mon and $mon >= 1 and $mon <= 12
!ll&&!rl&&r
219
defined $mon and $mon >= 1
!ll&&!rl&&r
1110
MC/DC100%3/3
defined $mon and $mon >= 1 and $mon <= 12
defined $mon $mon >= 1 $mon <= 12
Truth table100%4/4
A and B and C
A= defined $monB= $mon >= 1C= $mon <= 12
ABCresult
0XX0
10X0
1100
1111
439  
440 my $epoch = _epoch_of($part->{Y} + 0, $mon, $part->{d} + 0,
441 9 ▶ ($part->{H} // 0) + 0, ($part->{M} // 0) + 0, ($part->{S} // 0) + 0);
Condition83%5/6
$part->{"H"} // 0
l!l
27
$part->{"M"} // 0
l!l
27
$part->{"S"} // 0
l!l
09
MC/DC100%1/1
$part->{"H"} // 0
$part->{"H"}
MC/DC100%1/1
$part->{"M"} // 0
$part->{"M"}
MC/DC0%0/1
$part->{"S"} // 0
$part->{"S"}
Truth table100%2/2
A
A= $part->{"H"}
Aresult
11
00
Truth table100%2/2
A
A= $part->{"M"}
Aresult
11
00
Truth table50%1/2
A
A= $part->{"S"}
Aresult
11
00
442 9 ▶ return undef unless defined $epoch;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $epoch 2 7 9
443 7 ▶ return { epoch => $epoch, has_time => defined $part->{H} ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
defined $part->{'H'} ? : 2 5 7
444 }
445  
446 # _iso_second_label($epoch) -> 'YYYY-MM-DDTHH:MM:SS' in local time
447 6 ▶sub _iso_second_label {
Subroutine _iso_second_label: called CC=1 SCAR=0.0
448 6 my @lt = localtime($_[0]);
449 6 return sprintf '%04d-%02d-%02dT%02d:%02d:%02d',
450 $lt[5] + 1900, $lt[4] + 1, $lt[3], $lt[2], $lt[1], $lt[0];
451 }
452  
453 # _civil_day($y, $mon, $day) -> days since 1970-01-01
454 #
455 # Purpose: A day number that does not move with daylight saving, so the n-day
456 # and n-week buckets can be counted from a fixed origin. Integer
457 # civil-calendar arithmetic; no part of this reads the clock.
458 17 ▶sub _civil_day {
Subroutine _civil_day: called CC=4 SCAR=13.9
459 17 my ($y, $mon, $day) = @_;
460 17 ▶ $y -= ($mon <= 2) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$mon <= 2 ? : 4 13 17
461 17 ▶ my $era = int(($y >= 0 ? $y : $y - 399) / 400);
Branch: 1 branch
BranchTrueFalseTotal
$y >= 0 ? : 17 0 17
462 17 my $yoe = $y - $era * 400; # [0, 399]
463 17 ▶ my $doy = int((153 * ($mon + ($mon > 2 ? -3 : 9)) + 2) / 5) + $day - 1;
Branch: 1 branch
BranchTrueFalseTotal
$mon > 2 ? : 13 4 17
464 17 my $doe = $yoe * 365 + int($yoe / 4) - int($yoe / 100) + $doy;
465 17 return $era * 146_097 + $doe - 719_468;
466 }
467  
468 # _shift_days($y, $mon, $day, $delta) -> ($y, $mon, $day)
469 #
470 # Purpose: Move a date by whole days without a calendar library.
471 # Notes: Noon is the anchor. A day is then 86,400 seconds away from its
472 # neighbours even across a daylight-saving change, so counting days
473 # cannot land on the wrong date -- counting from midnight does, once a
474 # year, and only in the autumn.
475 13 ▶sub _shift_days {
Subroutine _shift_days: called CC=2 SCAR=6.9
476 13 my ($y, $mon, $day, $delta) = @_;
477 13 ▶ return ($y, $mon, $day) unless $delta;
Branch: 1 branch
BranchTrueFalseTotal
unless $delta 5 8 13
478 8 local $!; # mktime and localtime may set errno; see _epoch_of
479 8 require POSIX;
480 8 my @lt = localtime(POSIX::mktime(12, 0, 0, $day, $mon - 1, $y - 1900) + $delta * 86_400);
481 8 return ($lt[5] + 1900, $lt[4] + 1, $lt[3]);
482 }
483  
484 # span_interval($interval) -> { n => N, unit => U, [secs => S] } | undef
485 #
486 # Purpose: The interval vocabulary span() takes, and the only place its rule
487 # lives: a count and a unit, 'mon' for months (because 'm' is
488 # minutes) and 'q' for quarters. A count below one and an unknown
489 # unit are both undef rather than a bucket that quietly means
490 # something else. Public because the span= sugar validates an
491 # interval before it builds the expression, and one rule with two
492 # callers beats two rules that drift apart.
493 83 ▶sub span_interval {
Subroutine span_interval: called CC=10 SCAR=23.0
Pod undocumented
494 83 my ($interval) = @_;
495 83 ▶ return undef unless defined $interval && !ref $interval && length $interval;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $interval and not ref $interval and length $interval 3 80 83
Condition100%6/6
defined $interval and not ref $interval and length $interval
!ll&&!rl&&r
2180
defined $interval and not ref $interval
!ll&&!rl&&r
1181
MC/DC100%3/3
defined $interval and not ref $interval and length $interval
defined $interval not ref $interval length $interval
Truth table100%4/4
A and not(B) and C
A= defined $intervalB= not ref $intervalC= length $interval
ABCresult
0XX0
10X0
1100
1111
496 80 ▶ my ($n, $unit) = $interval =~ /\A(\d+)(mon|s|m|h|d|w|q|y)\z/ or return undef;
Branch: 1 branch
BranchTrueFalseTotal
() = $interval =~ /\A(\d+)(mon|s|m|h|d|w|q|y)\z/ or return undef 52 28 80
497 52 $n += 0;
498 52 ▶ return undef if $n < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 1 2 50 52
499  
500 50 ▶ my $secs = $unit eq 's' ? 1
Branch: 3 branches
BranchTrueFalseTotal
$unit eq 's' ? : 2 48 50
$unit eq 'm' ? : 2 46 48
$unit eq 'h' ? : 2 44 46
501 : $unit eq 'm' ? 60
502 : $unit eq 'h' ? 3_600
503 : undef;
504 50 ▶ return { n => $n, unit => $unit, (defined $secs ? (secs => $secs) : ()) };
Branch: 1 branch
BranchTrueFalseTotal
defined $secs ? : 6 44 50
505 }
506  
507 # compile_pattern($pattern) -> \%compiled
508 #
509 # Purpose: The one place a reader's regular expression is checked and compiled,
510 # for rx() and for the stored extractions, so both refuse the same
511 # things with the same words.
512 # Entry: $pattern is a string.
513 # Exit: { re => qr//, groups => N, names => [ named groups, in order ] }.
514 # Croaks error_pattern_too_long, error_pattern_construct or
515 # error_pattern_invalid.
516 # Notes: A pattern is checked, not sandboxed: the engine has no timeout, so a
517 # pathological one stalls the request that uses it. Patterns are typed
518 # by the reader who owns the machine, never taken from a remote party.
519 36 ▶sub compile_pattern {
Subroutine compile_pattern: called CC=12 SCAR=25.0
Pod undocumented
520 36 my ($pattern) = @_;
521 36 local $@;
522 36 ▶ $pattern = '' unless defined $pattern && !ref $pattern;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pattern and not ref $pattern 4 32 36
Condition100%3/3
defined $pattern and not ref $pattern
!ll&&!rl&&r
2232
MC/DC100%2/2
defined $pattern and not ref $pattern
defined $pattern not ref $pattern
Truth table100%3/3
A and not(B)
A= defined $patternB= not ref $pattern
ABresult
0X0
100
111
523 36 ▶ croak _fmt('error_pattern_too_long', substr($pattern, 0, 40) . (length($pattern) > 40 ? '...' : ''), $MAX_PATTERN_LEN)
Branch: 2 branches
BranchTrueFalseTotal
if length $pattern > $MAX_PATTERN_LEN 1 35 36
length $pattern > 40 ? : 1 0 1
524 if length($pattern) > $MAX_PATTERN_LEN;
525 35 ▶ if ($pattern =~ $REFUSED_PATTERN_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern =~ /$REFUSED_PATTERN_RE/) 7 28 35
526 7 croak _fmt('error_pattern_construct', $pattern, $1);
527 }
528  
529 28 my $re = eval { qr/$pattern/ };
530 28 ▶ unless ($re) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($re) 5 23 28
531 5 ▶ (my $why = $@ // '') =~ s/ at \S+ line \d+\.?\n?\z//;
Condition50%1/2
$@ // ""
l!l
50
MC/DC0%0/1
$@ // ""
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
532 5 $why =~ s/\s+\z//;
533 5 croak _fmt('error_pattern_invalid', $pattern, $why);
534 }
535  
536 # An optional match of the empty string always succeeds, and leaves behind
537 # how many groups the pattern has and every name it declares.
538 23 '' =~ /(?:$re)?/;
539 23 my $groups = $#+;
540 23 require re;
541 23 my %known = map { $_ => 1 } re::regnames(1);
542 # The names in the order they are written, which is the order a reader
543 # expects the columns in; regnames() itself has no order.
544 23 my (@names, %seen);
545 23 ▶ while ($pattern =~ /(?<!\\)\(\?(?:P?<([A-Za-z_]\w*)>|'([A-Za-z_]\w*)')/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern =~ /(?<!\\)\(\?(?:P?<([A-Za-z_]\w*)>|'([A-Za-z_]\w*)')/g) 16 23 39
546 16 ▶ my $n = defined $1 ? $1 : $2;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 15 1 16
547 16 ▶ push @names, $n if $known{$n} && !$seen{$n}++;
Branch: 1 branch
BranchTrueFalseTotal
if $known{$n} and not $seen{$n}++ 16 0 16
Condition33%1/3
$known{$n} and not $seen{$n}++
!ll&&!rl&&r
0016
MC/DC0%0/2
$known{$n} and not $seen{$n}++
$known{$n} not $seen{$n}++
Truth table33%1/3
A and not(B)
A= $known{$n}B= not $seen{$n}++
ABresult
0X0
100
111
548 }
549 23 push @names, grep { !$seen{$_}++ } sort keys %known;
550  
551 23 return { re => $re, groups => $groups, names => \@names };
552 }
553  
554 # capture_of(\%compiled, $value, $group) -> $capture | undef
555 #
556 # Purpose: One capture of a compiled pattern against a value: $group is a
557 # number (1 is the first group) or a group's name.
558 # Exit: The capture, cut to $MAX_CAPTURE_LEN characters; '' when the pattern
559 # matched but the group took no part; undef when the value is undefined,
560 # the pattern does not match, or there is no such group.
561 19 ▶sub capture_of {
Subroutine capture_of: called CC=13 SCAR=25.6
Pod undocumented
562 19 my ($compiled, $value, $group) = @_;
563 19 ▶ return undef unless defined $value && !ref $value && defined $group;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and defined $group 3 16 19
Condition100%6/6
defined $value and not ref $value and defined $group
!ll&&!rl&&r
2116
defined $value and not ref $value
!ll&&!rl&&r
1117
MC/DC100%3/3
defined $value and not ref $value and defined $group
defined $value not ref $value defined $group
Truth table100%4/4
A and not(B) and C
A= defined $valueB= not ref $valueC= defined $group
ABCresult
0XX0
10X0
1100
1111
564 # Which group is asked for is settled first: a match of its own here would
565 # replace the captures of the one that matters.
566 16 ▶ my $number = $group =~ /\A[0-9]+\z/ ? $group + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$group =~ /\A[0-9]+\z/ ? : 8 8 16
567 16 ▶ if (defined $number) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $number) { } 8 8 16
568 8 ▶ return undef if $number < 1 || $number > $compiled->{groups};
Branch: 1 branch
BranchTrueFalseTotal
if $number < 1 or $number > $compiled->{"groups"} 2 6 8
Condition100%3/3
$number < 1 or $number > $compiled->{"groups"}
l!l&&r!l&&!r
116
MC/DC100%2/2
$number < 1 or $number > $compiled->{"groups"}
$number < 1 $number > $compiled->{"groups"}
Truth table100%3/3
A or B
A= $number < 1B= $number > $compiled->{"groups"}
ABresult
1X1
011
000
569 } else {
570 8 ▶ return undef unless grep { $_ eq $group } @{ $compiled->{names} };
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $group;} @{$$compiled{"names"};} 2 6 8
571 }
572 12 ▶ return undef unless $value =~ $compiled->{re};
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /$compiled->{"re"}/ 2 10 12
573 10 ▶ my $got = defined $number ? ${^CAPTURE}[$number - 1] : $+{$group};
Branch: 1 branch
BranchTrueFalseTotal
defined $number ? : 5 5 10
574 10 ▶ return '' unless defined $got;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got 2 8 10
575 8 ▶ return length($got) > $MAX_CAPTURE_LEN ? substr($got, 0, $MAX_CAPTURE_LEN) : $got;
Branch: 1 branch
BranchTrueFalseTotal
length $got > $MAX_CAPTURE_LEN ? : 1 7 8
576 }
577  
578 # _span_label($value, \%interval) -> bucket label | undef
579 #
580 # Purpose: The ISO label of the bucket a value falls in -- the half-open
581 # interval from the bucket's start to the next bucket's start.
582 # Notes: The label is ISO at the bucket's own resolution, never 'Oct 2026':
583 # group keys are sorted as strings, so an ISO label makes
584 # lexicographic order chronological order and a bucketed chart comes
585 # out in the right order with no second sort path. A pretty name is a
586 # presentation step (month_name() already reads a month number); it is
587 # never the key.
588 # The intervals below a day are floored out of the epoch, and 'd'
589 # downwards are counted in calendar units, because a day is not always
590 # 86,400 seconds and a month never is.
591 31 ▶sub _span_label {
Subroutine _span_label: called CC=9 SCAR=22.0
592 31 my ($value, $interval) = @_;
593 31 my $t = _parse_time($value);
594 31 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 5 26 31
595  
596 26 my $n = $interval->{n};
597 26 my $unit = $interval->{unit};
598  
599 26 ▶ if (defined $interval->{secs}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $interval->{"secs"}) 3 23 26
600 3 my $step = $n * $interval->{secs};
601 3 return _iso_second_label(floor($t->{epoch} / $step) * $step);
602 }
603  
604 23 my @lt = localtime($t->{epoch});
605 23 my ($y, $mon, $day) = ($lt[5] + 1900, $lt[4] + 1, $lt[3]);
606  
607 23 ▶ if ($unit eq 'd') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "d") 5 18 23
608 5 ▶ return sprintf('%04d-%02d-%02d', $y, $mon, $day) if $n == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 1 1 4 5
609 4 my $day_no = _civil_day($y, $mon, $day);
610 4 return sprintf('%04d-%02d-%02d', _shift_days($y, $mon, $day, -($day_no % $n)));
611 }
612  
613 18 ▶ if ($unit eq 'w') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "w") 5 13 18
614 # Monday is the first day of the ISO week, and 1970-01-05 is the
615 # Monday the week count runs from.
616 5 require POSIX;
617 5 local $!; # mktime and localtime may set errno; see _epoch_of
618 5 my $dow = (localtime(POSIX::mktime(12, 0, 0, $day, $mon - 1, $y - 1900)))[6];
619 5 my $day_no = _civil_day($y, $mon, $day);
620 5 ▶ my $monday = $day_no - ($dow == 0 ? 6 : $dow - 1);
Branch: 1 branch
BranchTrueFalseTotal
$dow == 0 ? : 1 4 5
621 5 my $weeks = floor(($monday - 4) / 7);
622 5 my $start = $monday - ($weeks % $n) * 7;
623 5 return sprintf('%04d-%02d-%02d', _shift_days($y, $mon, $day, $start - $day_no));
624 }
625  
626 # A month count runs from January 1970, and a quarter count from its first
627 # quarter, so the buckets line up with the calendar at every width and not
628 # only when the count is one.
629 13 ▶ if ($unit eq 'mon') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "mon") 6 7 13
630 6 my $idx = ($y - 1970) * 12 + ($mon - 1);
631 6 my $lo = $idx - ($idx % $n);
632 6 return sprintf('%04d-%02d-01', 1970 + floor($lo / 12), $lo % 12 + 1);
633 }
634  
635 7 ▶ if ($unit eq 'q') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "q") 5 2 7
636 5 my $qi = ($y - 1970) * 4 + int(($mon - 1) / 3);
637 5 my $lo = $qi - ($qi % $n);
638 5 return sprintf('%04d-%02d-01', 1970 + floor($lo / 4), ($lo % 4) * 3 + 1);
639 }
640  
641 2 return sprintf('%04d-01-01', $y - ($y % $n));
642 }
643  
644 # ---------------------------------------------------------------------------
645 # Constructor
646 # ---------------------------------------------------------------------------
647  
648 313 ▶sub new {
Subroutine new: called CC=12 SCAR=24.8
Pod documented
649 313 my ($class, %args) = @_;
650 # A bad expression is an answer here, not an exception, so nothing of the
651 # compile may reach the caller's $@.
652 313 local $@;
653 # Takes off the where-it-happened tail that croak adds. A path can hold spaces,
654 # and this text reaches the reader, so the tail is everything from the last
655 # " at " on rather than one word.
656 55 ▶ my $tidy = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
657 55 my ($err) = @_;
658 55 $err =~ s/\A(.*) at .+? line \d+\.?\n?\z/$1/s;
659 55 return $err;
660 313 };
661  
662 313 my $self = bless {
663 _error => undef,
664 _code => undef,
665 _columns => {},
666 _params => {},
667 }, $class;
668  
669 313 ▶ my $expr = $args{expr} // '';
Condition100%2/2
$args{"expr"} // ""
l!l
3121
MC/DC100%1/1
$args{"expr"} // ""
$args{"expr"}
Truth table100%2/2
A
A= $args{"expr"}
Aresult
11
00
670 313 ▶ my @cols = @{ $args{columns} // [] };
Condition100%2/2
$args{"columns"} // []
l!l
3058
MC/DC100%1/1
$args{"columns"} // []
$args{"columns"}
Truth table100%2/2
A
A= $args{"columns"}
Aresult
11
00
671 313 ▶ my %params = %{ $args{params} // {} };
Condition100%2/2
$args{"params"} // {}
l!l
18295
MC/DC100%1/1
$args{"params"} // {}
$args{"params"}
Truth table100%2/2
A
A= $args{"params"}
Aresult
11
00
672 313 $self->{_columns}{$_} = 1 for @cols;
673  
674 # A name that is both a column and a parameter is an error: the ambiguity
675 # would be resolved silently in whichever direction, making expressions
676 # non-deterministic when the data changes.
677 313 for my $p (keys %params) {
678 3 ▶ if ($self->{_columns}{$p}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_columns"}{$p}) 1 2 3
679 1 $self->{_error} = _fmt('error_param_col_clash', $p);
680 1 return $self;
681 }
682 }
683 # Extend the compile-time column whitelist with param names so _parse_colref
684 # accepts them as identifiers; at evaluate() time their values come from
685 # _params rather than the row hashref.
686 312 $self->{_columns}{$_} = 1 for keys %params;
687 312 $self->{_params} = \%params;
688  
689 312 ▶ if (length($expr) > $MAX_EXPR_LEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $expr > $MAX_EXPR_LEN) 2 310 312
690 2 $self->{_error} = _fmt('error_expr_too_long', $MAX_EXPR_LEN);
691 2 return $self;
692 }
693  
694 310 my $tokens;
695 310 my $ok = eval { $tokens = _tokenize($expr); 1 };
696 310 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 10 300 310
697 10 $self->{_error} = $tidy->($@);
698 10 return $self;
699 }
700  
701 300 my $pos = 0;
702 300 my $depth = 0;
703 300 my $code;
704 300 $ok = eval { $code = _parse_cmp($tokens, \$pos, \$depth, $self->{_columns}); 1 };
705 300 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 45 255 300
706 45 $self->{_error} = $tidy->($@);
707 45 return $self;
708 }
709  
710 255 ▶ if ($tokens->[$pos]{type} ne $T_EOF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tokens->[$pos]{"type"} ne $T_EOF) 3 252 255
711 $self->{_error} = _fmt('error_trailing',
712 3 $tokens->[$pos]{val}, $tokens->[$pos]{pos});
713 3 return $self;
714 }
715  
716 252 $self->{_code} = $code;
717 252 return $self;
718 }
719  
720 # ---------------------------------------------------------------------------
721 # Public API
722 # ---------------------------------------------------------------------------
723  
724 59 ▶sub error { $_[0]->{_error} }
Subroutine error: called CC=1 SCAR=0.0
Pod documented
725 273 ▶sub has_error { defined $_[0]->{_error} }
Subroutine has_error: called CC=1 SCAR=0.0
Pod documented
726  
727 271 ▶sub evaluate {
Subroutine evaluate: called CC=6 SCAR=17.9
Pod documented
728 271 my ($self, $row) = @_;
729 271 ▶ return undef unless defined $self->{_code};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_code"} 2 269 271
730 269 ▶ $row //= {};
Condition100%2/2
$row //= {}
l!l
2672
MC/DC100%1/1
$row //= {}
$row
Truth table100%2/2
A
A= $row
Aresult
11
00
731 269 ▶ return undef unless ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 1 268 269
732 268 local $@; # a failed row is undef, and the caller's $@ is its own
733 268 local $!; # the date functions call mktime and localtime, which may set errno
734 # Merge bound parameters into the evaluation context. Parameters take
735 # precedence over same-named columns: the clash check in new() ensures this
736 # never happens legitimately, but a column added to the data after compile
737 # time should still see the parameter value.
738 268 my $ctx = %{ $self->{_params} }
739 268 ▶ ? { %$row, %{ $self->{_params} } }
Branch: 1 branch
BranchTrueFalseTotal
%{$self->{'_params'};} ? : 4 264 268
740 : $row;
741 268 my $result;
742 268 my $ok = eval { $result = $self->{_code}->($ctx); 1 };
743 268 ▶ return undef unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 3 265 268
744 265 return $result;
745 }
746  
747 # ---------------------------------------------------------------------------
748 # Tokenizer
749 # ---------------------------------------------------------------------------
750  
751 330 ▶sub _tokenize {
Subroutine _tokenize: called CC=18 SCAR=28.9
752 330 my ($expr) = @_;
753 330 my @tokens;
754 330 my $pos = 0;
755 330 my $len = length($expr);
756 330 my %single_ops = (
757 '+' => $T_PLUS, '-' => $T_MINUS,
758 '*' => $T_STAR, '/' => $T_SLASH,
759 '(' => $T_LPAREN, ')' => $T_RPAREN, ',' => $T_COMMA,
760 );
761  
762 330 ▶ while ($pos < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len) 3487 302 3789
763 3487 my $ch = substr($expr, $pos, 1);
764  
765 # skip whitespace
766 3487 ▶ if ($ch =~ /\A\s/) { $pos++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($ch =~ /\A\s/) 312 3175 3487
767  
768 # number literal (integer, decimal, scientific)
769 3175 ▶ if (substr($expr, $pos) =~ /\A(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($expr, $pos) =~ /\A(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/) 444 2731 3175
770 444 push @tokens, { type => $T_NUM, val => $1, pos => $pos };
771 444 $pos += length($1);
772 444 next;
773 }
774  
775 # double-quoted string
776 2731 ▶ if ($ch eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "\"") 7 2724 2731
777 7 my $end = index($expr, '"', $pos + 1);
778 7 ▶ croak _fmt('error_unterminated', $pos) if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 2 5 7
779 5 push @tokens, {
780 type => $T_STR,
781 val => substr($expr, $pos + 1, $end - $pos - 1),
782 pos => $pos,
783 };
784 5 $pos = $end + 1;
785 5 next;
786 }
787  
788 # single-quoted string
789 2724 ▶ if ($ch eq "'") {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "'") 61 2663 2724
790 61 my $end = index($expr, "'", $pos + 1);
791 61 ▶ croak _fmt('error_unterminated', $pos) if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 1 60 61
792 60 push @tokens, {
793 type => $T_STR,
794 val => substr($expr, $pos + 1, $end - $pos - 1),
795 pos => $pos,
796 };
797 60 $pos = $end + 1;
798 60 next;
799 }
800  
801 # identifier: letters/digits/underscore, leading letter or _
802 2663 ▶ if (substr($expr, $pos) =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($expr, $pos) =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)/) 445 2218 2663
803 445 push @tokens, { type => $T_IDENT, val => $1, pos => $pos };
804 445 $pos += length($1);
805 445 next;
806 }
807  
808 # two-character comparison operators (must be tested before single-char)
809 2218 ▶ if ($pos + 1 < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos + 1 < $len) 2019 199 2218
810 2019 my $two = substr($expr, $pos, 2);
811 2019 ▶ if ($two eq '!=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq "!=") 5 2014 2019
812 5 push @tokens, { type => $T_NEQ, val => '!=', pos => $pos };
813 5 $pos += 2; next;
814 }
815 2014 ▶ if ($two eq '<=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq "<=") 6 2008 2014
816 6 push @tokens, { type => $T_LE, val => '<=', pos => $pos };
817 6 $pos += 2; next;
818 }
819 2008 ▶ if ($two eq '>=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq ">=") 6 2002 2008
820 6 push @tokens, { type => $T_GE, val => '>=', pos => $pos };
821 6 $pos += 2; next;
822 }
823 2002 ▶ if ($two eq '==') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq "==") 2 2000 2002
824 2 croak _fmt('error_double_eq', $pos);
825 }
826 }
827  
828 # single-character comparison operators
829 2199 ▶ if ($ch eq '=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "=") 9 2190 2199
830 9 push @tokens, { type => $T_EQ, val => '=', pos => $pos };
831 9 $pos++; next;
832 }
833 2190 ▶ if ($ch eq '<') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "<") 9 2181 2190
834 9 push @tokens, { type => $T_LT, val => '<', pos => $pos };
835 9 $pos++; next;
836 }
837 2181 ▶ if ($ch eq '>') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq ">") 12 2169 2181
838 12 push @tokens, { type => $T_GT, val => '>', pos => $pos };
839 12 $pos++; next;
840 }
841  
842 # single-character arithmetic operators and punctuation
843 2169 ▶ if (exists $single_ops{$ch}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $single_ops{$ch}) 2146 23 2169
844 2146 push @tokens, { type => $single_ops{$ch}, val => $ch, pos => $pos };
845 2146 $pos++;
846 2146 next;
847 }
848  
849 23 croak _fmt('error_bad_char', $ch, $pos);
850 }
851  
852 302 push @tokens, { type => $T_EOF, val => '', pos => $pos };
853 302 return \@tokens;
854 }
855  
856 # ---------------------------------------------------------------------------
857 # Parser (each _parse_* returns a coderef sub { my ($row) = @_; ... })
858 # ---------------------------------------------------------------------------
859  
860 1270 ▶sub _check_depth {
Subroutine _check_depth: called CC=2 SCAR=6.9
861 1270 my ($depth_ref) = @_;
862 1270 ▶ croak _fmt('error_expr_too_deep', $MAX_DEPTH) if $$depth_ref >= $MAX_DEPTH;
Branch: 1 branch
BranchTrueFalseTotal
if $$depth_ref >= $MAX_DEPTH 6 1264 1270
863 }
864  
865 174 ▶sub _expect {
Subroutine _expect: called CC=2 SCAR=6.9
866 174 my ($tokens, $pos_ref, $expected) = @_;
867 174 my $tok = $tokens->[$$pos_ref];
868 croak _fmt('error_expected_tok', $expected, $tok->{pos}, $tok->{val})
869 174 ▶ unless $tok->{type} eq $expected;
Branch: 1 branch
BranchTrueFalseTotal
unless $tok->{"type"} eq $expected 3 171 174
870 171 $$pos_ref++;
871 }
872  
873 # cmp_expr ::= add_expr (cmp_op add_expr)?
874 # Comparison yields 1 (true), 0 (false), or undef (either operand undef).
875 # When both operands look numeric, numeric comparison is used; otherwise
876 # case-insensitive string comparison, matching _apply_filter_spec semantics.
877 585 ▶sub _parse_cmp {
Subroutine _parse_cmp: called CC=7 SCAR=19.5
878 585 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
879 585 _check_depth($depth_ref);
880 582 $$depth_ref++;
881  
882 582 my $left = _parse_add($tokens, $pos_ref, $depth_ref, $cols);
883  
884 510 my $type = $tokens->[$$pos_ref]{type};
885 510 ▶ if ($type eq $T_EQ || $type eq $T_NEQ
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT or $type eq $T_GE) 40 470 510
Condition100%15/15
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT or $type eq $T_GE
l!l&&r!l&&!r
355470
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT
l!l&&r!l&&!r
2411475
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE
l!l&&r!l&&!r
195486
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT
l!l&&r!l&&!r
127491
$type eq $T_EQ or $type eq $T_NEQ
l!l&&r!l&&!r
84498
MC/DC100%6/6
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT or $type eq $T_GE
$type eq $T_EQ $type eq $T_NEQ $type eq $T_LT $type eq $T_LE $type eq $T_GT $type eq $T_GE
Truth table100%7/7
A or B or C or D or E or F
A= $type eq $T_EQB= $type eq $T_NEQC= $type eq $T_LTD= $type eq $T_LEE= $type eq $T_GTF= $type eq $T_GE
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
886 || $type eq $T_LT || $type eq $T_LE
887 || $type eq $T_GT || $type eq $T_GE) {
888 40 my $op = $type;
889 40 $$pos_ref++;
890 40 my $right = _parse_add($tokens, $pos_ref, $depth_ref, $cols);
891 40 my ($l, $r) = ($left, $right);
892 38 ▶ $left = sub {
Subroutine __ANON__: called CC=27 SCAR=33.4
893 38 my $lv = $l->($_[0]);
894 38 my $rv = $r->($_[0]);
895 38 ▶ return undef unless defined $lv && defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and defined $rv 3 35 38
Condition100%3/3
defined $lv and defined $rv
!ll&&!rl&&r
2135
MC/DC100%2/2
defined $lv and defined $rv
defined $lv defined $rv
Truth table100%3/3
A and B
A= defined $lvB= defined $rv
ABresult
0X0
100
111
896 35 ▶ if (looks_like_number($lv) && looks_like_number($rv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&looks_like_number($lv) and &looks_like_number($rv)) { } 27 8 35
Condition66%2/3
&looks_like_number($lv) and &looks_like_number($rv)
!ll&&!rl&&r
8027
MC/DC50%1/2
&looks_like_number($lv) and &looks_like_number($rv)
&looks_like_number($lv) &looks_like_number($rv)
Truth table66%2/3
A and B
A= &looks_like_number($lv)B= &looks_like_number($rv)
ABresult
0X0
100
111
897 27 ▶ return $op eq $T_EQ ? ($lv == $rv ? 1 : 0)
Branch: 11 branches
BranchTrueFalseTotal
$op eq $T_EQ ? : 3 24 27
$lv == $rv ? : 2 1 3
$op eq $T_NEQ ? : 3 21 24
$lv != $rv ? : 1 2 3
$op eq $T_LT ? : 4 17 21
$lv < $rv ? : 1 3 4
$op eq $T_LE ? : 4 13 17
$lv <= $rv ? : 3 1 4
$op eq $T_GT ? : 9 4 13
$lv > $rv ? : 6 3 9
$lv >= $rv ? : 2 2 4
898 : $op eq $T_NEQ ? ($lv != $rv ? 1 : 0)
899 : $op eq $T_LT ? ($lv < $rv ? 1 : 0)
900 : $op eq $T_LE ? ($lv <= $rv ? 1 : 0)
901 : $op eq $T_GT ? ($lv > $rv ? 1 : 0)
902 : ($lv >= $rv ? 1 : 0);
903 } else {
904 8 my $cmp = lc($lv) cmp lc($rv);
905 8 ▶ return $op eq $T_EQ ? ($cmp == 0 ? 1 : 0)
Branch: 11 branches
BranchTrueFalseTotal
$op eq $T_EQ ? : 2 6 8
$cmp == 0 ? : 2 0 2
$op eq $T_NEQ ? : 1 5 6
$cmp != 0 ? : 0 1 1
$op eq $T_LT ? : 2 3 5
$cmp < 0 ? : 2 0 2
$op eq $T_LE ? : 1 2 3
$cmp <= 0 ? : 1 0 1
$op eq $T_GT ? : 1 1 2
$cmp > 0 ? : 0 1 1
$cmp >= 0 ? : 1 0 1
906 : $op eq $T_NEQ ? ($cmp != 0 ? 1 : 0)
907 : $op eq $T_LT ? ($cmp < 0 ? 1 : 0)
908 : $op eq $T_LE ? ($cmp <= 0 ? 1 : 0)
909 : $op eq $T_GT ? ($cmp > 0 ? 1 : 0)
910 : ($cmp >= 0 ? 1 : 0);
911 }
912 40 };
913 }
914  
915 510 $$depth_ref--;
916 510 return $left;
917 }
918  
919 # add_expr ::= term ( ('+' | '-') term )*
920 622 ▶sub _parse_add {
Subroutine _parse_add: called CC=4 SCAR=13.9
921 622 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
922 622 _check_depth($depth_ref);
923 622 $$depth_ref++;
924  
925 622 my $left = _parse_term($tokens, $pos_ref, $depth_ref, $cols);
926  
927 551 ▶ while ($tokens->[$$pos_ref]{type} eq $T_PLUS
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_PLUS or $$tokens[$$pos_ref]{"type"} eq $T_MINUS) 229 550 779
Condition100%3/3
$$tokens[$$pos_ref]{"type"} eq $T_PLUS or $$tokens[$$pos_ref]{"type"} eq $T_MINUS
l!l&&r!l&&!r
2236550
MC/DC100%2/2
$$tokens[$$pos_ref]{"type"} eq $T_PLUS or $$tokens[$$pos_ref]{"type"} eq $T_MINUS
$$tokens[$$pos_ref]{"type"} eq $T_PLUS $$tokens[$$pos_ref]{"type"} eq $T_MINUS
Truth table100%3/3
A or B
A= $$tokens[$$pos_ref]{"type"} eq $T_PLUSB= $$tokens[$$pos_ref]{"type"} eq $T_MINUS
ABresult
1X1
011
000
928 || $tokens->[$$pos_ref]{type} eq $T_MINUS) {
929 229 my $op = $tokens->[$$pos_ref]{type};
930 229 $$pos_ref++;
931 229 my $right = _parse_term($tokens, $pos_ref, $depth_ref, $cols);
932 228 my ($l, $r) = ($left, $right);
933 228 ▶ if ($op eq $T_PLUS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq $T_PLUS) { } 222 6 228
934 $left = sub {
935 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
936 return undef unless defined $lv && defined $rv;
937 return undef unless looks_like_number($lv) && looks_like_number($rv);
938 $lv + $rv;
939 222 };
940 } else {
941 $left = sub {
942 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
943 return undef unless defined $lv && defined $rv;
944 return undef unless looks_like_number($lv) && looks_like_number($rv);
945 $lv - $rv;
946 6 };
947 }
948 }
949  
950 550 $$depth_ref--;
951 550 return $left;
952 }
953  
954 # term ::= factor ( ('*' | '/') factor )*
955 851 ▶sub _parse_term {
Subroutine _parse_term: called CC=4 SCAR=13.9
956 851 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
957  
958 851 my $left = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
959  
960 779 ▶ while ($tokens->[$$pos_ref]{type} eq $T_STAR
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_STAR or $$tokens[$$pos_ref]{"type"} eq $T_SLASH) 26 779 805
Condition100%3/3
$$tokens[$$pos_ref]{"type"} eq $T_STAR or $$tokens[$$pos_ref]{"type"} eq $T_SLASH
l!l&&r!l&&!r
1511779
MC/DC100%2/2
$$tokens[$$pos_ref]{"type"} eq $T_STAR or $$tokens[$$pos_ref]{"type"} eq $T_SLASH
$$tokens[$$pos_ref]{"type"} eq $T_STAR $$tokens[$$pos_ref]{"type"} eq $T_SLASH
Truth table100%3/3
A or B
A= $$tokens[$$pos_ref]{"type"} eq $T_STARB= $$tokens[$$pos_ref]{"type"} eq $T_SLASH
ABresult
1X1
011
000
961 || $tokens->[$$pos_ref]{type} eq $T_SLASH) {
962 26 my $op = $tokens->[$$pos_ref]{type};
963 26 $$pos_ref++;
964 26 my $right = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
965 26 my ($l, $r) = ($left, $right);
966 26 ▶ if ($op eq $T_STAR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq $T_STAR) { } 15 11 26
967 $left = sub {
968 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
969 return undef unless defined $lv && defined $rv;
970 return undef unless looks_like_number($lv) && looks_like_number($rv);
971 $lv * $rv;
972 15 };
973 } else {
974 $left = sub {
975 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
976 return undef unless defined $lv && defined $rv;
977 return undef unless looks_like_number($lv) && looks_like_number($rv);
978 return undef if $rv == 0;
979 $lv / $rv;
980 11 };
981 }
982 }
983  
984 779 return $left;
985 }
986  
987 # factor ::= unary | '(' cmp_expr ')' | number | string | column | call
988 936 ▶sub _parse_factor {
Subroutine _parse_factor: called CC=8 SCAR=20.8
989 936 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
990 936 my $tok = $tokens->[$$pos_ref];
991  
992 # unary minus
993 936 ▶ if ($tok->{type} eq $T_MINUS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_MINUS) 40 896 936
994 40 $$pos_ref++;
995 40 _check_depth($depth_ref);
996 39 $$depth_ref++;
997 39 my $inner = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
998 21 $$depth_ref--;
999 return sub {
1000 my $v = $inner->($_[0]);
1001 return undef unless defined $v && looks_like_number($v);
1002 -$v;
1003 21 };
1004 }
1005  
1006 # unary plus (no-op)
1007 896 ▶ if ($tok->{type} eq $T_PLUS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_PLUS) 21 875 896
1008 21 $$pos_ref++;
1009 21 _check_depth($depth_ref);
1010 20 $$depth_ref++;
1011 20 my $inner = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
1012 2 $$depth_ref--;
1013 2 return $inner;
1014 }
1015  
1016 # parenthesized sub-expression: allow full cmp_expr so (qty > 0) works
1017 875 ▶ if ($tok->{type} eq $T_LPAREN) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_LPAREN) 28 847 875
1018 28 $$pos_ref++;
1019 28 my $inner = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1020 8 _expect($tokens, $pos_ref, $T_RPAREN);
1021 7 return $inner;
1022 }
1023  
1024 # number literal
1025 847 ▶ if ($tok->{type} eq $T_NUM) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_NUM) 411 436 847
1026 411 my $val = $tok->{val} + 0;
1027 411 $$pos_ref++;
1028 411 return sub { $val };
1029 }
1030  
1031 # string literal
1032 436 ▶ if ($tok->{type} eq $T_STR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_STR) 47 389 436
1033 47 my $val = $tok->{val};
1034 47 $$pos_ref++;
1035 47 return sub { $val };
1036 }
1037  
1038 # identifier -- function call or column reference
1039 389 ▶ if ($tok->{type} eq $T_IDENT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_IDENT) 385 4 389
1040 385 my $name = $tok->{val};
1041 385 $$pos_ref++;
1042 return $tokens->[$$pos_ref]{type} eq $T_LPAREN
1043 ? _parse_call($tokens, $pos_ref, $depth_ref, $cols, $name, $tok->{pos})
1044 385 ▶ : _parse_colref($cols, $name, $tok->{pos});
Branch: 1 branch
BranchTrueFalseTotal
$$tokens[$$pos_ref]{'type'} eq $T_LPAREN ? : 187 198 385
1045 }
1046  
1047 4 croak _fmt('error_unexpected_tok', $tok->{val}, $tok->{pos});
1048 }
1049  
1050 # Parse a function call. 'if' is a special form (short-circuit branches).
1051 # Arguments may be full cmp_expr (e.g. IF(qty > 0, amount/qty, 0)).
1052 187 ▶sub _parse_call {
Subroutine _parse_call: called CC=23 SCAR=38.1
1053 187 my ($tokens, $pos_ref, $depth_ref, $cols, $name, $name_pos) = @_;
1054 187 my $lc = lc($name);
1055  
1056 croak _fmt('error_unknown_fn', $name)
1057 187 ▶ unless exists $FUNCTIONS{$lc} || $lc eq 'if' || $lc eq 'rx' || $TIME_CONST_FNS{$lc};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx" or $TIME_CONST_FNS{$lc} 11 176 187
Condition88%8/9
exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx" or $TIME_CONST_FNS{$lc}
l!l&&r!l&&!r
1651111
exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx"
l!l&&r!l&&!r
165022
exists $FUNCTIONS{$lc} or $lc eq "if"
l!l&&r!l&&!r
1511422
MC/DC75%3/4
exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx" or $TIME_CONST_FNS{$lc}
exists $FUNCTIONS{$lc} $lc eq "if" $lc eq "rx" $TIME_CONST_FNS{$lc}
Truth table80%4/5
A or B or C or D
A= exists $FUNCTIONS{$lc}B= $lc eq "if"C= $lc eq "rx"D= $TIME_CONST_FNS{$lc}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1058  
1059 # rx(v, 'pattern' [, 'group']): the pattern and the group are constants,
1060 # so the pattern is checked and compiled once, here. A group the pattern
1061 # does not have is undef on every row rather than an error, as the POD says.
1062 176 ▶ if ($lc eq 'rx') {
Branch: 1 branch
BranchTrueFalseTotal
if ($lc eq "rx") 0 176 176
1063 0 $$pos_ref++; # consume '('
1064 0 my $value_fn = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1065 0 my @const;
1066 0 ▶ while ($tokens->[$$pos_ref]{type} eq $T_COMMA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_COMMA) 0 0 0
1067 0 $$pos_ref++;
1068 0 my $tok = $tokens->[$$pos_ref];
1069 croak _fmt('error_rx_args')
1070 0 ▶ unless $tok->{type} eq $T_STR || $tok->{type} eq $T_NUM;
Branch: 1 branch
BranchTrueFalseTotal
unless $tok->{"type"} eq $T_STR or $tok->{"type"} eq $T_NUM 0 0 0
Condition0%0/3
$tok->{"type"} eq $T_STR or $tok->{"type"} eq $T_NUM
l!l&&r!l&&!r
000
MC/DC0%0/2
$tok->{"type"} eq $T_STR or $tok->{"type"} eq $T_NUM
$tok->{"type"} eq $T_STR $tok->{"type"} eq $T_NUM
Truth table0%0/3
A or B
A= $tok->{"type"} eq $T_STRB= $tok->{"type"} eq $T_NUM
ABresult
1X1
011
000
1071 0 push @const, $tok->{val};
1072 0 $$pos_ref++;
1073 }
1074 0 _expect($tokens, $pos_ref, $T_RPAREN);
1075 0 ▶ croak _fmt('error_rx_args') unless @const == 1 || @const == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @const == 1 or @const == 2 0 0 0
Condition0%0/3
@const == 1 or @const == 2
l!l&&r!l&&!r
000
MC/DC0%0/2
@const == 1 or @const == 2
@const == 1 @const == 2
Truth table0%0/3
A or B
A= @const == 1B= @const == 2
ABresult
1X1
011
000
1076 0 my $compiled = compile_pattern($const[0]);
1077 0 ▶ my $group = defined $const[1] ? $const[1] : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $const[1] ? : 0 0 0
1078 0 ▶ return sub { capture_of($compiled, $value_fn->($_[0]), $group) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
1079 }
1080  
1081 # epoch(v [, fmt]) and span(v, interval) take a constant second argument:
1082 # a format or an interval. It is checked here, once per column rather than
1083 # once per row, so a bad one is a compile error that names it -- and the
1084 # pattern is compiled once instead of on every value.
1085 176 ▶ if ($TIME_CONST_FNS{$lc}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TIME_CONST_FNS{$lc}) 11 165 176
1086 11 $$pos_ref++; # consume '('
1087 11 my $value_fn = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1088 11 my $const;
1089 11 ▶ if ($tokens->[$$pos_ref]{type} eq $T_COMMA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_COMMA) 8 3 11
1090 8 $$pos_ref++;
1091 8 my $tok = $tokens->[$$pos_ref];
1092 croak _fmt('error_const_arg', $name)
1093 8 ▶ unless $tok->{type} eq $T_STR;
Branch: 1 branch
BranchTrueFalseTotal
unless $tok->{"type"} eq $T_STR 2 6 8
1094 6 $const = $tok->{val};
1095 6 $$pos_ref++;
1096 }
1097 9 _expect($tokens, $pos_ref, $T_RPAREN);
1098  
1099 9 ▶ if ($lc eq 'epoch') {
Branch: 1 branch
BranchTrueFalseTotal
if ($lc eq "epoch") 5 4 9
1100 5 ▶ my $compiled = defined $const ? _fmt_compile($const) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $const ? : 3 2 5
1101 0 ▶ return sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1102 0 my $value = $value_fn->($_[0]);
1103 0 ▶ my $t = defined $compiled
Branch: 1 branch
BranchTrueFalseTotal
defined $compiled ? : 0 0 0
1104 ? _time_from_format($value, $compiled)
1105 : _parse_time($value);
1106 0 ▶ return defined $t ? $t->{epoch} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $t ? : 0 0 0
1107 4 };
1108 }
1109  
1110 4 ▶ my $interval = defined $const ? span_interval($const) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $const ? : 3 1 4
1111 4 ▶ croak _fmt('error_span_interval', defined $const ? $const : '')
Branch: 2 branches
BranchTrueFalseTotal
unless $interval 2 2 4
defined $const ? : 1 1 2
1112 unless $interval;
1113 0 ▶ return sub { _span_label($value_fn->($_[0]), $interval) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
1114 }
1115  
1116 165 $$pos_ref++; # consume '('
1117 165 my @arg_fns;
1118 165 ▶ if ($tokens->[$$pos_ref]{type} ne $T_RPAREN) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} ne $T_RPAREN) 161 4 165
1119 161 push @arg_fns, _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1120 151 ▶ while ($tokens->[$$pos_ref]{type} eq $T_COMMA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_COMMA) 85 151 236
1121 85 $$pos_ref++;
1122 85 push @arg_fns, _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1123 }
1124 }
1125 155 _expect($tokens, $pos_ref, $T_RPAREN);
1126  
1127 # 'if' special form: short-circuit true/false branches
1128 154 ▶ if ($lc eq 'if') {
Branch: 1 branch
BranchTrueFalseTotal
if ($lc eq "if") 14 140 154
1129 14 my ($cond_fn, $true_fn, $false_fn) = @arg_fns;
1130 7 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1131 7 ▶ $cond_fn->($_[0]) ? $true_fn->($_[0]) : $false_fn->($_[0]);
Branch: 1 branch
BranchTrueFalseTotal
&$cond_fn($_[0]) ? : 3 4 7
1132 14 };
1133 }
1134  
1135 140 my $fn = $FUNCTIONS{$lc};
1136 42 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1137 42 my $row = $_[0];
1138 42 $fn->(map { $_->($row) } @arg_fns);
1139 140 };
1140 }
1141  
1142 # Parse a column reference; validates against the whitelist at compile time.
1143 # Underscores in the expression may match spaces in the actual column name,
1144 # and the comparison is case-insensitive, so per_unit_price can address
1145 # a column named "Per Unit Price".
1146 198 ▶sub _parse_colref {
Subroutine _parse_colref: called CC=4 SCAR=13.9
1147 198 my ($cols, $name, $name_pos) = @_;
1148  
1149 # 1. Exact match
1150 198 ▶ return sub { $_[0]->{$name} } if $cols->{$name};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if $cols->{$name} 176 22 198
1151  
1152 # 2. Underscore-to-space alias, case-insensitive
1153 22 (my $spaced = $name) =~ s/_/ /g;
1154 22 my $lc_spaced = lc($spaced);
1155 22 for my $col (keys %{$cols}) {
1156 54 ▶ if (lc($col) eq $lc_spaced) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $col eq $lc_spaced) 4 50 54
1157 4 my $lookup = $col;
1158 4 ▶ return sub { $_[0]->{$lookup} };
Subroutine __ANON__: called CC=1 SCAR=0.0
1159 }
1160 }
1161  
1162 18 croak _fmt('error_unknown_col', $name);
1163 }
1164  
1165 # ---------------------------------------------------------------------------
1166 # Standalone date-normalisation helper (used by Dashboard::_apply_date_normalization)
1167 # ---------------------------------------------------------------------------
1168  
1169 # _iso_day_label($epoch) -> 'YYYY-MM-DD' in local time
1170 2 ▶sub _iso_day_label {
Subroutine _iso_day_label: called CC=1 SCAR=0.0
1171 2 my @lt = localtime($_[0]);
1172 2 return sprintf '%04d-%02d-%02d', $lt[5] + 1900, $lt[4] + 1, $lt[3];
1173 }
1174  
1175 # _normalise_with_format($value, \%pattern) -> ISO string or undef
1176 #
1177 # The hash shape of a stored pattern: { date => '<fmt>', [time => '<fmt'>],
1178 # [as => 'timestamp'] }. With a time pattern the value is normalised to
1179 # 'YYYY-MM-DDTHH:MM:SS', which is the shape the date comparisons already read
1180 # to the second; with as => 'timestamp' and no time pattern it is that same
1181 # shape at midnight, so a date-only column can be compared against a
1182 # last_24_hours window.
1183 12 ▶sub _normalise_with_format {
Subroutine _normalise_with_format: called CC=11 SCAR=24.0
1184 12 my ($val, $pattern) = @_;
1185 12 ▶ return undef unless defined $pattern->{date} && length $pattern->{date};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pattern->{"date"} and length $pattern->{"date"} 2 10 12
Condition100%3/3
defined $pattern->{"date"} and length $pattern->{"date"}
!ll&&!rl&&r
1110
MC/DC100%2/2
defined $pattern->{"date"} and length $pattern->{"date"}
defined $pattern->{"date"} length $pattern->{"date"}
Truth table100%3/3
A and B
A= defined $pattern->{"date"}B= length $pattern->{"date"}
ABresult
0X0
100
111
1186  
1187 # The pattern is stored JSON and the caller has no eval: one that cannot be
1188 # compiled is an unknown pattern, which is undef, not a 500 on every page.
1189 10 my $time_fmt = $pattern->{time};
1190 10 ▶ if (defined $time_fmt && length $time_fmt) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $time_fmt and length $time_fmt) 3 7 10
Condition66%2/3
defined $time_fmt and length $time_fmt
!ll&&!rl&&r
703
MC/DC50%1/2
defined $time_fmt and length $time_fmt
defined $time_fmt length $time_fmt
Truth table66%2/3
A and B
A= defined $time_fmtB= length $time_fmt
ABresult
0X0
100
111
1191 3 ▶ my $compiled = eval { _fmt_compile_pair($pattern->{date}, $time_fmt) } or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $compiled = eval { do { _fmt_compile_pair($pattern->{"date"}, $time_fmt) } } or return undef 2 1 3
1192 2 my $t = _time_from_format($val, $compiled);
1193 2 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 1 2
1194 1 return _iso_second_label($t->{epoch});
1195 }
1196  
1197 7 ▶ my $compiled = eval { _fmt_compile($pattern->{date}) } or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $compiled = eval { do { _fmt_compile($pattern->{"date"}) } } or return undef 4 3 7
1198 4 my $t = _time_from_format($val, $compiled);
1199 4 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 2 2 4
1200 return ($pattern->{as} // '') eq 'timestamp'
1201 ? _iso_second_label($t->{epoch})
1202 2 ▶ : _iso_day_label($t->{epoch});
Branch: 1 branch
BranchTrueFalseTotal
($pattern->{'as'} // '') eq 'timestamp' ? : 1 1 2
Condition100%2/2
$pattern->{"as"} // ""
l!l
11
MC/DC100%1/1
$pattern->{"as"} // ""
$pattern->{"as"}
Truth table100%2/2
A
A= $pattern->{"as"}
Aresult
11
00
1203 }
1204  
1205 # _iso_date_if_real($y, $mon, $day) -> 'YYYY-MM-DD' or undef
1206 #
1207 # A UK file read with the US pattern has "months" up to 31. Undef sends it to the
1208 # '(unparseable)' bucket, where it can be seen; "2026-15-01" looks like a date and
1209 # sorts among the real ones.
1210 30 ▶sub _iso_date_if_real {
Subroutine _iso_date_if_real: called CC=2 SCAR=6.9
1211 30 my ($y, $mon, $day) = @_;
1212 30 ▶ return undef unless defined _epoch_of($y + 0, $mon + 0, $day + 0, 12, 0, 0);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _epoch_of($y + 0, $mon + 0, $day + 0, 12, 0, 0) 12 18 30
1213 18 return sprintf('%04d-%02d-%02d', $y, $mon, $day);
1214 }
1215  
1216 # date_normalise($value, $pattern) -> ISO string or undef
1217 #
1218 # Converts $value from the given strptime-style $pattern to ISO-8601.
1219 # Returns undef when $value does not match the pattern or the pattern is
1220 # unknown. No external modules required.
1221 #
1222 # $pattern is either one of the three date patterns below, or a hashref
1223 # { date => ..., time => ..., as => ... } for a column that holds a time as
1224 # well as a date; see _normalise_with_format.
1225 #
1226 # Supported date patterns:
1227 # %m/%d/%Y -- US slash-date (01/15/2026)
1228 # %d/%m/%Y -- EU slash-date (15/01/2026)
1229 # %d-%b-%Y -- DD-Mon-YYYY (15-Jan-2026, case-insensitive month abbrev)
1230 51 ▶sub date_normalise {
Subroutine date_normalise: called CC=12 SCAR=24.8
Pod undocumented
1231 51 my ($val, $pattern) = @_;
1232 51 local $!; # mktime and localtime may set errno; see _epoch_of
1233 51 ▶ return undef unless defined $val && defined $pattern && length $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and defined $pattern and length $val 6 45 51
Condition100%6/6
defined $val and defined $pattern and length $val
!ll&&!rl&&r
4245
defined $val and defined $pattern
!ll&&!rl&&r
2247
MC/DC100%3/3
defined $val and defined $pattern and length $val
defined $val defined $pattern length $val
Truth table100%4/4
A and B and C
A= defined $valB= defined $patternC= length $val
ABCresult
0XX0
10X0
1100
1111
1234 45 ▶ return _normalise_with_format($val, $pattern) if ref $pattern eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $pattern eq "HASH" 12 33 45
1235 33 ▶ if ($pattern eq '%m/%d/%Y') {
Branch: 3 branches
BranchTrueFalseTotal
if ($pattern eq '%m/%d/%Y') { } 13 20 33
elsif ($pattern eq '%d/%m/%Y') { } 9 11 20
elsif ($pattern eq '%d-%b-%Y') { } 9 2 11
1236 13 ▶ return undef unless $val =~ /\A(\d{1,2})\/(\d{1,2})\/(\d{4})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z] 3 10 13
1237 10 return _iso_date_if_real($3, $1, $2);
1238 } elsif ($pattern eq '%d/%m/%Y') {
1239 9 ▶ return undef unless $val =~ /\A(\d{1,2})\/(\d{1,2})\/(\d{4})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z] 2 7 9
1240 7 return _iso_date_if_real($3, $2, $1);
1241 } elsif ($pattern eq '%d-%b-%Y') {
1242 9 ▶ return undef unless $val =~ /\A(\d{1,2})-([A-Za-z]{3})-(\d{4})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ /\A(\d{1,2})-([A-Za-z]{3})-(\d{4})\z/ 2 7 9
1243 7 my $mon = $_MONTH_NAME_TO_NUM{lc($2)};
1244 7 ▶ return undef unless defined $mon;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mon 2 5 7
1245 5 return _iso_date_if_real($3, $mon, $1);
1246 }
1247 2 return undef;
1248 }
1249  
1250 2 1;
1251  
1252 __END__
« script/database-bi ↑ Summary blib/lib/Database/BI/Summary.pm »