Arithmetic/Pegex.pm

filter: Statementstmt 100% 34 / 34 Branchbran 75.0% 12 / 16 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod 100% 1 / 1 totaltotal 93.2% 55 / 59 CC 9 SCAR 17.3
CC
9
Cov
92%
gotrule
9.3
BEGIN
1.0
BEGIN
1.0
CRAP 5.7
↑ Summary Arithmetic.pm »
1 package PERLANCAR::Parse::Arithmetic::Pegex;
2  
3 2 our $DATE = '2016-06-18'; # DATE
4 2 our $VERSION = '0.004'; # VERSION
5  
6 2 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 2 ▶use Pegex;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 2 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 our @EXPORT_OK = qw(parse_arithmetic);
14  
15 2 my $grammar = <<'...';
16 # Precedence Climbing grammar:
17 expr: add-sub
18 add-sub: mul-div+ % /- ( [ '+-' ])/
19 mul-div: power+ % /- ([ '*/' ])/
20 power: token+ % /- '**' /
21 token: /- '(' -/ expr /- ')'/ | number
22 number: /- ( '-'? DIGIT+ '.'? DIGIT* )/
23 ...
24  
25 {
26 package
27 Calculator;
28 2 ▶ use base 'Pegex::Tree';
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 41 ▶ sub gotrule {
Subroutine gotrule: called CC=9 SCAR=22.3
31 41 my ($self, $list) = @_;
32 41 ▶ return $list unless ref $list;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list 22 19 41
33  
34 # Right associative:
35 19 ▶ if ($self->rule eq 'power') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rule eq 'power') { } 8 11 19
36 8 ▶ while (@$list > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$list > 1) 2 8 10
37 2 my ($a, $b) = splice(@$list, -2, 2);
38 2 push @$list, $a ** $b;
39 }
40 }
41 # Left associative:
42 else {
43 11 ▶ while (@$list > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$list > 1) 4 11 15
44 4 my ($a, $op, $b) = splice(@$list, 0, 3);
45 4 ▶ unshift @$list,
Branch: 4 branches
BranchTrueFalseTotal
$op eq '+' ? : 2 2 4
$op eq '-' ? : 0 2 2
$op eq '*' ? : 2 0 2
$op eq '/' ? : 0 0 0
46 ($op eq '+') ? ($a + $b) :
47 ($op eq '-') ? ($a - $b) :
48 ($op eq '*') ? ($a * $b) :
49 ($op eq '/') ? ($a / $b) :
50 die;
51 }
52 }
53 19 return @$list;
54 }
55 }
56  
57 2 ▶sub parse_arithmetic {
Subroutine parse_arithmetic: called CC=1 SCAR=0.0
Pod documented
58 3 pegex($grammar, 'Calculator')->parse($_[0]);
59 }
60  
61 2 1;
62 # ABSTRACT: Parse arithmetic expression (Pegex version)
63  
64 __END__
↑ Summary Arithmetic.pm »