Evaluator/Parser.pm

filter: Statementstmt 97.9% 145 / 148 Branchbran 96.6% 58 / 60 Conditioncond 100% 3 / 3 MC/DCmcdc 100% 2 / 2 Subroutinesub 96.1% 25 / 26 Podpod 100% 1 / 1 totaltotal 97.5% 234 / 240 CC 32 SCAR 11.4
CC
32
Cov
98%
_term
5.0
_statement
5.0
_expression
5.0
CRAP 3.1
« Evaluator/Lexer.pm ↑ Summary Evaluator/Util.pm »
1 package Math::Expression::Evaluator::Parser;
2  
3 =head1 NAME
4  
5 Math::Expression::Evaluator::Parser - Parse mathematical expressions
6  
7 =head1 SYNOPSIS
8  
9 use Math::Expression::Evaluator::Parser;
10 my $exp = '2 + a * 4';
11 my $ast = Math::Expression::Evaluator::Parser::parse($exp, {});
12 # $ast is now something like this:
13 # $ast = ['+',
14 # 2,
15 # ['*',
16 # ['$', 'a'],
17 # 4
18 # ]
19 # ];
20  
21 =head1 DESCRIPTION
22  
23 This module parses a mathematical expression in usual notation, and
24 turns it into an Abstract Syntax Tree (AST).
25  
26 If you want to have a simple interface and want to evaluate these
27 ASTs, use L<Math::Expression::Evaluator>.
28  
29 The following description of the AST structure matches the current
30 implementation, but really is an implementation detail that's subject to
31 change without further notice. In particular a possible addition of meta
32 information (like file and line numbers) might require a change of structure.
33  
34 The AST is a tree that consists of nested array refs. The first item
35 is a string (until now always a single character), and denotes the type
36 of the node. The rest of the items in the array is a list of its arguments.
37  
38 For the mathematical symbols C<+>, C<->, C<*>, C</>, C<^> (exponentation)
39 this is straight forward, but C</> and C<-> are always treated as prefix ops,
40 so the string '2 - 3' is actually turned into C<['+', 2, ['-', 3]]>.
41  
42 Other AST nodes are
43  
44 =over 4
45  
46 =item '$'
47  
48 C<['$', $var_name]> represents a variable.
49  
50 =item '{'
51  
52 C<['{', $expr1, $expr2, ... ]> represents a block, i.e. a list of expressions.
53  
54 =item '='
55  
56 C<['=', $var, $expr]> represents an assignment, where C<$expr> is assigned
57 to C<$var>.
58  
59 =item '&'
60  
61 C<['&', $name, @args]> is a function toll to the function called C<$name>.
62  
63 =back
64  
65 =head1 METHODS
66  
67 =over
68  
69 =item parse
70  
71 C<parse> takes a string and a hash ref, where the hash ref takes
72 configuration parameters. Currently the only allowed option is
73 C<force_semicolon>. If set to a true value, it forces statements to
74 be forced by semicolons (so C<2 3> will be forbidden, C<2; 3> is still
75 allowed).
76  
77 C<parse> throws an exception on parse errors.
78  
79 =back
80  
81 =cut
82  
83 17 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
84 17 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
85  
86 17 ▶use Math::Expression::Evaluator::Lexer qw(lex);
Subroutine BEGIN: called CC=1 SCAR=0.0
87 17 ▶use Math::Expression::Evaluator::Util qw(is_lvalue);
Subroutine BEGIN: called CC=1 SCAR=0.0
88 17 ▶use Carp qw(confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
89 17 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
90  
91  
92 my @input_tokens = (
93 ['ExpOp' => '\^|\*\*'],
94 ['MulOp' => qr{[*/%]}],
95 ['AddOp' => '\+|-'],
96 # This regex is 'stolen' from Regexp::Common, and a bit simplified
97 # Copyright by Damian Conway and Abigail, 2001-2005
98 ['Float' => "[+-]?(?=[0-9]|[.])[0-9]*(?:[.][0-9]*)?(?:[eE](?:[+-]?[0-9]+)|)"],
99 ['OpenParen' => '\('],
100 ['ClosingParen' => '\)'],
101 ['Colon' => ';'],
102 ['Comma' => ','],
103 ['AssignmentOp' => '='],
104 ['Name' => '[a-zA-Z_][a-zA-Z_0-9]*'],
105 232 ▶ ['Whitespace' => '\s+', sub {return undef}],
Subroutine __ANON__: called CC=1 SCAR=0.0
106 0 ▶ ['Comment' => qr/\#.*?$/, sub {return undef}],
Subroutine __ANON__: not called CC=1 SCAR=1.2
107 );
108  
109 17 my %token_description = (
110 ExpOp => 'Operator',
111 MulOp => 'Operator',
112 AddOp => 'Operator',
113 AssignmentOp => 'Operator',
114 Float => 'Term',
115 Name => 'Term',
116 );
117  
118 291 ▶sub parse {
Subroutine parse: called CC=1 SCAR=0.0
Pod documented
119  
120 291 my ($text, $parse_opts) = @_;
121  
122 # note that this object is only used internally, to the
123 # world outside we hide it.
124 291 my $self = bless {};
125 291 $self->{config} = $parse_opts;
126 291 $self->{tokens} = lex($text, \@input_tokens);
127 290 $self->{token_pointer} = 0;
128 290 return $self->_program();
129  
130 }
131  
132 # checks if the next token is what you expected, for example
133 # _is_next_token("AddOp") checks if the next token is a '+' or '-'
134 4578 ▶sub _is_next_token {
Subroutine _is_next_token: called CC=3 SCAR=11.0
135 4578 my $self = shift;
136 4578 my $cmp = shift;
137 4578 my $next = $self->{tokens}[$self->{token_pointer}];
138 4578 ▶ if (defined $next && $next->[0] eq $cmp){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $next and $next->[0] eq $cmp) 499 4079 4578
Condition100%3/3
defined $next and $next->[0] eq $cmp
!ll&&!rl&&r
13632716499
MC/DC100%2/2
defined $next and $next->[0] eq $cmp
defined $next $next->[0] eq $cmp
Truth table100%3/3
A and B
A= defined $nextB= $next->[0] eq $cmp
ABresult
0X0
100
111
139 499 return $next->[1];
140 }
141 }
142  
143 # basically the same _is_next_token, but does an arbitrary number of lookahead
144 # steps.
145 1252 ▶sub _lookahead {
Subroutine _lookahead: called CC=4 SCAR=13.9
146 1252 my $self = shift;
147 1252 my $i = 0;
148 1252 ▶ while (my $v = shift){
Branch: 1 branch
BranchTrueFalseTotal
if (my $v = shift()) 1422 91 1513
149 1422 ▶ return undef unless($self->{tokens}[$self->{token_pointer}+$i]);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"tokens"}[$self->{"token_pointer"} + $i] 25 1397 1422
150 1397 my $ref = $self->{tokens}[$self->{token_pointer} + $i]->[0];
151 1397 ▶ return undef unless($ref eq $v);
Branch: 1 branch
BranchTrueFalseTotal
unless $ref eq $v 1136 261 1397
152 261 $i++;
153 }
154 91 return 1;
155 }
156  
157 # move the token pointer one step further.
158 1340 ▶sub _proceed {
Subroutine _proceed: called CC=1 SCAR=0.0
159 1340 my $self = shift;
160 1340 $self->{token_pointer}++;
161 }
162  
163 # returns the next not-yet-parsed token
164 2645 ▶sub _next_token {
Subroutine _next_token: called CC=1 SCAR=0.0
165 2645 return $_[0]->{tokens}[$_[0]->{token_pointer}];
166 }
167  
168 # program -> statement*
169 # parse a program, e.g. a collection of statements.
170 # The corrsponding AST looks like this: ['{', $s1, $s2, $s3, ... ]
171 290 ▶sub _program {
Subroutine _program: called CC=2 SCAR=6.9
172 290 my $self = shift;
173 290 my @res = ('{');
174 290 ▶ while (defined $self->_next_token()){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->_next_token) 304 277 581
175 304 push @res, $self->_statement();
176 }
177 277 return _return_simplify(@res);
178 }
179  
180 # generates an error message that something was expected but not found,
181 # for example 'a + +' would warn that a value was expected, but an AddOp
182 # was found.
183 4 ▶sub _expected {
Subroutine _expected: called CC=2 SCAR=7.6
184 4 my $self = shift;
185 4 ▶ if (scalar @_ > 1){
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ > 1) { } 4 0 4
186 4 confess("Parse error: Expected $_[0]; got: '$_[1]'\n"
187 . "near character " . $self->_next_token->[2] . "\n");
188 } else {
189 0 confess("Parse error: Expected $_[0]\n"
190 . "near character " . $self->_next_token->[2] . "\n");
191 }
192 }
193  
194 # matches a specific token, and returns its text if successfull. Dies if
195 # unsuccessfull.
196 1031 ▶sub _match {
Subroutine _match: called CC=3 SCAR=11.0
197 1031 my $self = shift;
198 1031 my $m = shift;
199 1031 my $val;
200 1031 my $next = $self->_next_token();
201 1031 ▶ confess("Expected $m, got EOF") unless ref $next;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $next 6 1025 1031
202 1025 ▶ if ($next->[0] eq $m){
Branch: 1 branch
BranchTrueFalseTotal
if ($next->[0] eq $m) { } 1021 4 1025
203 1021 $val = $self->_next_token()->[1];
204 1021 $self->_proceed();
205 1021 return $val;
206 } else {
207 4 $self->_expected($m, $self->_next_token()->[0]);
208 }
209 }
210  
211 # <value> -> <float> | <name> | <function_call>
212 # parses a single value: a float, a function call or a variable name
213 # returns the corresponding AST.
214 708 ▶sub _value {
Subroutine _value: called CC=4 SCAR=13.9
215 708 my $self = shift;
216 708 ▶ if ($self->_lookahead("Name", "OpenParen")){
Branch: 3 branches
BranchTrueFalseTotal
if ($self->_lookahead('Name', 'OpenParen')) { } 85 623 708
elsif ($self->_is_next_token('Name')) { } 79 544 623
elsif ($self->_lookahead('AddOp', 'Float')) { } 6 538 544
217 85 return $self->_function_call();
218 } elsif ($self->_is_next_token("Name")){
219 79 return $self->_get_variable();
220 } elsif ($self->_lookahead(qw/AddOp Float/)) {
221 6 my $sign = $self->_match('AddOp');
222 6 return ("$sign".1) * $self->_match('Float');
223 } else {
224 538 return $self->_match("Float");
225 }
226 }
227  
228 # <function_call> -> <name> '(' [<expression> [',' <expression>]* ]? ')'
229 # parses a function call, the AST looks like this: ['&', $name, @args]
230 85 ▶sub _function_call {
Subroutine _function_call: called CC=4 SCAR=13.9
231 85 my $self = shift;
232 85 my @res = ('&', $self->_match("Name"));
233 85 $self->_match("OpenParen");
234 85 ▶ if ($self->_is_next_token("ClosingParen")){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_next_token("ClosingParen")) 8 77 85
235 8 $self->_proceed();
236 8 return \@res;
237 }
238 77 push @res, $self->_expression();
239 77 ▶ while ($self->_is_next_token("Comma")){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_next_token("Comma")) 4 75 79
240 4 $self->_proceed();
241 4 ▶ last if $self->_is_next_token('ClosingParen');
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_next_token("ClosingParen") 2 2 4
242 2 push @res, $self->_expression();
243 }
244 77 $self->_match("ClosingParen");
245 77 return \@res;
246 }
247  
248 # <name> -> m/[a-zA-Z_]\w*/
249 # parses a variable name, and returns it
250 79 ▶sub _get_variable {
Subroutine _get_variable: called CC=1 SCAR=0.0
251 79 my $self = shift;
252 79 my $var_name = $self->_match("Name");
253 79 return ['$', $var_name];
254 }
255  
256 # <statement> -> <_assignment> | <expression>
257 # parses a statement, eg an _assignment or an expression.
258 304 ▶sub _statement {
Subroutine _statement: called CC=5 SCAR=16.1
259 304 my $self = shift;
260 304 my $e = $self->_expression();
261 296 ▶ if ($self->_is_next_token("AssignmentOp")){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_next_token("AssignmentOp")) 10 286 296
262 10 $e = $self->_assignment($e);
263 }
264  
265 293 ▶ if ($self->{config}->{force_semicolon}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'config'}{'force_semicolon'}) { } 4 289 293
266 # forced semicolon between two statements (but the last statement
267 # isn't forced to have one):
268 4 ▶ if ($self->_next_token()){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_next_token) 3 1 4
269 3 $self->_match("Colon");
270 }
271 } else {
272 # optional semicolon at end of statement
273 289 ▶ if ($self->_is_next_token("Colon")){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_next_token("Colon")) 7 282 289
274 7 $self->_proceed();
275 }
276 }
277 291 return $e;
278 }
279  
280 # <_assignment> ::= <lvalue> '=' <expression>
281 # expects the lvalue as first argument
282 10 ▶sub _assignment {
Subroutine _assignment: called CC=2 SCAR=6.9
283 10 my $self = shift;
284 10 my $e = shift;
285 10 $self->_match("AssignmentOp");
286 10 my $val = $self->_expression();
287 10 ▶ if (is_lvalue($e)){
Branch: 1 branch
BranchTrueFalseTotal
if (is_lvalue($e)) { } 7 3 10
288 7 return ['=', $e, $val];
289 } else {
290 3 confess("Not an lvalue in _assignment");
291 }
292 }
293  
294  
295 # <term> ::= <exponential> [('*'|'/') <exponential>]*
296 # the AST is a bit weird, a simple product is expressed as
297 # ['*', $v1, $v2, ... ]
298 # a division is a bit more complex:
299 # a / b / c becomes ['*', a, ['/', b], ['/', c]]
300 568 ▶sub _term {
Subroutine _term: called CC=5 SCAR=16.1
301 568 my $self = shift;
302 568 my $val = $self->_exponential();
303 562 my @res = ('*', $val);
304 562 ▶ while (my $op = $self->_is_next_token("MulOp")){
Branch: 1 branch
BranchTrueFalseTotal
if (my $op = $self->_is_next_token("MulOp")) 157 560 717
305 157 ▶ if ($op eq '*'){
Branch: 3 branches
BranchTrueFalseTotal
if ($op eq '*') { } 87 70 157
elsif ($op eq '/') { } 37 33 70
elsif ($op eq '%') { } 33 0 33
306 87 $self->_proceed();
307 87 push @res, $self->_exponential();
308 } elsif ($op eq '/'){
309 37 $self->_proceed();
310 37 push @res, ['/', $self->_exponential()];
311 } elsif ($op eq '%') {
312 33 $self->_proceed();
313 # XXX not very efficient
314 33 @res = ('*', ['%', [@res], $self->_exponential()]);
315 } else {
316 0 die "Don't know how to handle MulOp $op\n";
317 }
318 }
319 560 return _return_simplify(@res);
320 }
321  
322 # <expression> ::= ['+'|'-']? <term> [('+'|'-') term]*
323 446 ▶sub _expression {
Subroutine _expression: called CC=5 SCAR=16.1
324 446 my $self = shift;
325 # print STDERR "expression...\n";
326 446 my @res = ('+');
327 446 ▶ if (my $op = $self->_is_next_token("AddOp")){
Branch: 1 branch
BranchTrueFalseTotal
if (my $op = $self->_is_next_token('AddOp')) { } 21 425 446
328 # unary +/-
329 21 $self->_proceed();
330 21 ▶ if ($op eq '+'){
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq '+') { } 4 17 21
331 4 push @res, $self->_term();
332 } else {
333 17 push @res, ['-', $self->_term()];
334 }
335 } else {
336 425 push @res, $self->_term();
337 }
338 441 ▶ while (my $op = $self->_is_next_token("AddOp")){
Branch: 1 branch
BranchTrueFalseTotal
if (my $op = $self->_is_next_token("AddOp")) 122 438 560
339 122 ▶ if ($op eq '+'){
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq '+') { } 95 27 122
340 95 $self->_proceed();
341 95 push @res, $self->_term();
342 } else {
343 # a '-'
344 27 $self->_proceed();
345 27 push @res, ['-', $self->_term()];
346 }
347 }
348 438 return _return_simplify(@res);
349 }
350  
351 # <factor> ::= <value> | '(' <expression> ')'
352 761 ▶sub _factor {
Subroutine _factor: called CC=2 SCAR=6.9
353 761 my $self = shift;
354 761 my $val;
355 761 ▶ if ($self->_is_next_token("OpenParen")){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_next_token('OpenParen')) { } 53 708 761
356 53 $self->_match("OpenParen");
357 53 $val = $self->_expression();
358 53 $self->_match("ClosingParen");
359 } else {
360 708 $val = $self->_value();
361 }
362 753 return $val;
363 }
364  
365 # <exponential> ::= <factor> [ '^' <factor>]?
366 # note that 2^3^4 is not defined, ie ^ is not associative
367 725 ▶sub _exponential {
Subroutine _exponential: called CC=2 SCAR=6.9
368 725 my $self = shift;
369 725 my $val = $self->_factor();
370 718 ▶ if ($self->_is_next_token("ExpOp")){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_next_token('ExpOp')) { } 36 682 718
371 36 $self->_match("ExpOp");
372 36 return ['^', $val, $self->_factor()];
373 } else {
374 682 return $val;
375 }
376 }
377  
378 1275 ▶sub _return_simplify {
Subroutine _return_simplify: called CC=2 SCAR=6.9
379 1275 ▶ return $_[1] if @_ == 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 2 1070 205 1275
380 205 return \@_;
381 }
382  
383  
384 17 1;
385 # vim: sw=4 ts=4 expandtab
« Evaluator/Lexer.pm ↑ Summary Evaluator/Util.pm »