Evaluator.pm

filter: Statementstmt 98.9% 383 / 387 Branchbran 90.4% 38 / 42 Conditioncond 100% 6 / 6 MC/DCmcdc 100% 3 / 3 Subroutinesub 99.2% 136 / 137 Podpod 100% 9 / 9 totaltotal 98.4% 575 / 584 CC 29 SCAR 4.4
CC
29
Cov
98%
new
4.0
_exec_function_call
4.0
ast_size
4.0
CRAP 1.6
« Evaluator/Util.pm ↑ Summary
1 package Math::Expression::Evaluator;
2 17 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 17 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 17 ▶use Math::Expression::Evaluator::Parser;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 17 ▶use Math::Expression::Evaluator::Util qw(is_lvalue);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 17 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 17 ▶use POSIX qw(ceil floor);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 17 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 17 ▶use Math::Trig qw(atan asin acos tan);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 17 our $VERSION = '0.3.2';
13  
14 =encoding UTF-8
15  
16 =head1 NAME
17  
18 Math::Expression::Evaluator - parses, compiles and evaluates mathematic expressions
19  
20 =head1 SYNOPSIS
21  
22 use Math::Expression::Evaluator;
23 my $m = Math::Expression::Evaluator->new;
24  
25 print $m->parse("a = 12; a*3")->val(), "\n";
26 # prints 36
27 print $m->parse("2^(a/3)")->val(), "\n";
28 # prints 8 (ie 2**3)
29 print $m->parse("a / b")->val({ b => 6 }), "\n";
30 # prints 36
31 print $m->parse("log2(16)")->val(), "\n";
32 # prints 4
33  
34 # if you care about speed
35 my $func = $m->parse('2 + (4 * b)')->compiled;
36 for (0 .. 100){
37 print $func->({b => $_}), "\n";
38 }
39  
40  
41 =head1 DESCRIPTION
42  
43 Math::Expression::Evaluator is a parser, compiler and interpreter for
44 mathematical expressions. It can handle normal arithmetics
45 (includings powers wit C<^> or C<**>), builtin functions like sin() and variables.
46  
47 Multiplication C<*>, division C</> and modulo C<%> have the same precedence,
48 and are evaluated left to right. The modulo operation follows the standard
49 perl semantics, that is is the arguments are castet to integer before
50 preforming the modulo operation.
51  
52 Multiple exressions can be seperated by whitespaces or by semicolons ';'.
53 In case of multiple expressions the value of the last expression is
54 returned.
55  
56 Variables can be assigned with a single '=' sign, their name has to start
57 with a alphabetic character or underscore C<[a-zA-Z_]>, and may contain
58 alphabetic characters, digits and underscores.
59  
60 Values for variables can also be provided as a hash ref as a parameter
61 to val(). In case of collision the explicitly provided value is used:
62  
63 $m->parse("a = 2; a")->val({a => 1});
64  
65 will return 1, not 2.
66  
67 The following builtin functions are supported atm:
68  
69 =over 4
70  
71 =item *
72  
73 trignometric functions: sin, cos, tan
74  
75 =item *
76  
77 inverse trigonomic functions: asin, acos, atan
78  
79 =item *
80  
81 Square root: sqrt
82  
83 =item *
84  
85 exponentials: exp, sinh, cosh
86  
87 =item *
88  
89 logarithms: log, log2, log10
90  
91 =item *
92  
93 constants: pi() (you need the parenthesis to distinguish it from the
94 variable pi)
95  
96 =item *
97  
98 rounding: ceil(), floor()
99  
100 =item *
101  
102 other: theta (theta(x) = 1 for x > 0, theta(x) = 0 for x < 0)
103  
104 =back
105  
106 =head1 METHODS
107  
108 =over 2
109  
110 =item new
111  
112 generates a new MathExpr object. accepts an optional argument, a hash ref
113 that contains configurations. If this hash sets force_semicolon to true,
114 expressions have to be separated by a semicolon ';'.
115  
116 =item parse
117  
118 Takes a string as argument, and generates an Abstract Syntax Tree(AST) that
119 is stored internally.
120  
121 Returns a reference to the object, so that method calls can be chained:
122  
123 print MathExpr->new->parse("1+2")->val;
124  
125 Parse failures cause this method to die with a stack trace.
126  
127 You can call C<parse> on an existing Math::Expression::Evaluator object to
128 re-use it, in which case previously set variables and callbacks persist
129 between calls.
130  
131 This (perhaps contrived) example explains this:
132  
133 my $m = Math::Expression::Evaluator->new('a = 3; a');
134 $m->val();
135 $m->parse('a + 5');
136 print $m->val(), "\n" # prints 8, because a = 3 was re-used
137  
138 If that's not what you want, create a new object instead - the constructor is
139 rather cheap.
140  
141 =item compiled
142  
143 Returns an anonymous function that is a compiled version of the current
144 expression. It is much faster to execute than the other methods, but its error
145 messages aren't as informative (instead of complaining about a non-existing
146 variable it dies with C<Use of uninitialized value in...>).
147  
148 Note that variables are not persistent between calls to compiled functions
149 (and it wouldn't make sense anyway, because such a function corresponds always
150 to exactly one expression, not many as a MEE object).
151  
152 Variables that were stored at the time when C<compiled()> is called are
153 availble in the compiled function, though.
154  
155 =item val
156  
157 Executes the AST generated by parse(), and returns the number that the
158 expression is evaluated to. It accepts an optional hash reference that
159 contain values for variables:
160  
161 my $m = MathExpr->new;
162 $m->parse("(x - 1) / (x + 1)");
163 foreach (0 .. 10) {
164 print $_, "\t", $m->val({x => $_}), "\n";
165 }
166  
167 =item optimize
168  
169 Optimizes the internal AST, so that subsequent calls to C<val()> will be
170 a bit faster. See C<Math::Expression::Evaluator::Optimizer> for performance
171 considerations and informations on the implemented optimizations.
172  
173 But note that a call to C<optimize()> only pays off if you call C<val()>
174 multiple times.
175  
176 =item variables
177  
178 C<variables()> returns a list of variables that are used in the expression.
179  
180 =item set_var_callback
181  
182 Allows you to set a callback which the Match::Expression::Evaluator object
183 calls when it can't find a variable. The name of the variable is passed in
184 as the first argument. If the callback function can't handle that variable
185 either, it should die, just like the default one does.
186  
187 my $m = Math::Expression::Evaluator->new();
188 $m->parse('1 + a');
189 my $callback = sub { ord($_[0]) };
190 $m->set_var_callback($callback);
191 print $m->val(); # calls $callback, which returns 97
192 # so $m->val() return 98
193  
194 The callback will be called every time the variable is accessed, so if it
195 requires expensive calculations, you are encouraged to cache it either
196 yourself our automatically with L<Memoize>.
197  
198 =item set_function
199  
200 Allows to add a user-defined function, or to override a built-in function.
201  
202 my $m = Math::Expression::Evaluator->new();
203 $m->set_function('abs', sub { abs($_[0]) });
204 $m->parse('abs(10.6)');
205 print $m->val();
206  
207 If you first compile the expression to a perl closure and then call
208 C<<$m->set_function>> again, the compiled function stays unaffected, so
209  
210 $m->set_function('f', sub { 42 });
211 my $compiled = $m->parse('f')->compiled;
212 $m->set_function('f', sub { -23 });
213 print $compiled->();
214  
215 print out C<42>, not C<-23>.
216  
217 =item ast_size
218  
219 C<ast_size> returns an integer which gives a crude measure of the logical
220 size of the expression. Note that this value isn't guarantueed to be stable
221 across multiple versions of this module. It is mainly intended for testing.
222  
223 =back
224  
225 =head1 SPEED
226  
227 MEE isn't as fast as perl, because it is built on top of perl.
228  
229 If you execute an expression multiple times, it pays off to either optimize
230 it first, or (even better) compile it to a pure perl function.
231  
232 Rate no_optimize optimize opt_compiled compiled
233 no_optimize 83.9/s -- -44% -82% -83%
234 optimize 150/s 78% -- -68% -69%
235 opt_compiled 472/s 463% 215% -- -4%
236 compiled 490/s 485% 227% 4% --
237  
238 This shows the time for 200 evaluations of C<2+a+5+(3+4)> (with MEE 0.0.5).
239 As you can see, the non-optimized version is painfully slow, optimization
240 nearly doubles the execution speed. The compiled and the
241 optimized-and-then-compiled versions are both much faster.
242  
243 With this example expression the optimization prior to compilation pays off
244 if you evaluate it more than 1000 times. But even if you call it C<10**5>
245 times the optimized and compiled version is only 3% faster than the directly
246 compiled one (mostly due to perl's overhead for method calls).
247  
248 So to summarize you should compile your expresions, and if you have really
249 many iterations it might pay off to optimize it first (or to write your
250 program in C instead ;-).
251  
252 =head1 BUGS AND LIMITATIONS
253  
254 =over 4
255  
256 =item *
257  
258 Modulo operator produces an unnecessary big AST, making it relatively slow
259  
260 =back
261  
262 =head1 INTERNALS
263  
264 The AST can be accessed as C<$obj->{ast}>. Its structure is described in
265 L<Math::Expression::Evaluator::Parser> (or you can use L<Data::Dumper>
266 to figure it out for yourself). Note that the exact form of the AST is
267 considered to be an implementation detail, and subject to change.
268  
269 =head1 SEE ALSO
270  
271 L<Math::Expression> also evaluates mathematical expressions, but also handles
272 string operations.
273  
274 If you want to do symbolic (aka algebraic) transformations, L<Math::Symbolic>
275 will fit your needs.
276  
277 =head1 LICENSE
278  
279 This module is free software. You may use, redistribute and modify it under
280 the same terms as perl itself.
281  
282 =head1 COPYRIGHT
283  
284 Copyright (C) 2007 - 2009 Moritz Lenz,
285 L<http://perlgeek.de/>, moritz@faui2k3.org
286  
287 =head1 DEVELOPMENT
288  
289 You can obtain the latest development version from github
290 L<http://github.com/moritz/math-expression-evaluator>.
291  
292 git clone git://github.com/moritz/math-expression-evaluator.git
293  
294 If you want to contribute something to this module, please ask me for
295 a commit bit to the github repository, I'm giving them out freely.
296  
297 =head1 ACKNOWLEDGEMENTS
298  
299 The following people have contributed to this module, in no particular order:
300  
301 =over
302  
303 =item Leonardo Herrera
304  
305 Initial patch for C<set_function>
306  
307 =item Tina Müller
308  
309 Helpful feedback
310  
311 =back
312  
313 =cut
314  
315 20 ▶sub new {
Subroutine new: called CC=4 SCAR=13.9
Pod documented
316 20 my $class = shift;
317 20 my $self = bless {}, $class;
318 20 $self->{tokens} = [];
319 20 $self->{variables} = {};
320 20 ▶ $self->{var_callback} = sub { confess "Variable '$_[0]' not defined" };
Subroutine __ANON__: called CC=1 SCAR=0.0
321  
322 20 my $first = shift;
323  
324 20 ▶ if (defined $first){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $first) 3 17 20
325 3 ▶ if (ref $first){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $first) { } 2 1 3
326 2 $self->{config} = $first;
327 2 ▶ $self->parse(shift) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 1 2
328 } else {
329 1 $self->parse($first);
330 }
331 }
332  
333 20 return $self;
334 }
335  
336  
337 # parse a text into an AST, stores the AST in $self->{ast}
338 291 ▶sub parse {
Subroutine parse: called CC=1 SCAR=0.0
Pod documented
339 291 my ($self, $text) = @_;
340 $self->{ast} =
341 291 Math::Expression::Evaluator::Parser::parse($text, $self->{config});
342 277 return $self;
343 }
344  
345  
346  
347 84 ▶sub optimize {
Subroutine optimize: called CC=1 SCAR=0.0
Pod documented
348 84 my ($self) = @_;
349 84 require Math::Expression::Evaluator::Optimizer;
350 84 $self->{ast} = Math::Expression::Evaluator::Optimizer::_optimize($self, $self->{ast});
351 84 return $self;
352 }
353  
354 # evaluates an arbitrary AST, and returns its value
355 865 ▶sub _execute {
Subroutine _execute: called CC=3 SCAR=11.1
356 865 my ($self, $ast) = @_;
357 my %dispatch = (
358 27 ▶ '/' => sub {1 / $_[0]->_execute($_[1])},
Subroutine __ANON__: called CC=1 SCAR=0.0
359 33 ▶ '-' => sub {-$_[0]->_execute($_[1])},
Subroutine __ANON__: called CC=1 SCAR=0.0
360 '+' => \&_exec_sum,
361 '*' => \&_exec_mul,
362 22 ▶ '%' => sub {$_[0]->_execute($_[1]) % $_[0]->_execute($_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
363 25 ▶ '^' => sub {$_[0]->_execute($_[1]) ** $self->_execute($_[2])},
Subroutine __ANON__: called CC=1 SCAR=0.0
364 0 ▶ '**' => sub {$_[0]->_execute($_[1]) ** $self->_execute($_[2])},
Subroutine __ANON__: not called CC=1 SCAR=6.9
365 '=' => \&_exec_assignment,
366 '&' => \&_exec_function_call,
367 '{' => \&_exec_block,
368 31 ▶ '$' => sub { my $self = shift; $self->_variable_lookup(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
369 865 );
370 # print STDERR "Executing " . Dumper($self->{ast});
371 865 ▶ if (ref $ast ){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ast) { } 358 507 865
372 358 my @a = @$ast;
373 358 my $op = shift @a;
374 358 ▶ if (my $fun = $dispatch{$op}){
Branch: 1 branch
BranchTrueFalseTotal
if (my $fun = $dispatch{$op}) { } 358 0 358
375 358 return &$fun($self, @a);
376 } else {
377 0 confess ("Operator '$op' not yet implemented\n");
378 }
379 } else {
380 507 $ast;
381 }
382 }
383  
384 1 ▶sub set_var_callback {
Subroutine set_var_callback: called CC=1 SCAR=0.0
Pod documented
385 1 $_[0]->{var_callback} = $_[1];
386 }
387  
388 # executes a sum
389 72 ▶sub _exec_sum {
Subroutine _exec_sum: called CC=2 SCAR=6.9
390 72 my $self = shift;
391 # avoid addition for unary plus, for overloaded objects
392 72 my $sum = $self->_execute(shift);
393 72 foreach (@_){
394 84 $sum = $sum + $self->_execute($_);
395 }
396 72 return $sum;
397 }
398  
399 # executes a value
400 181 ▶sub val {
Subroutine val: called CC=2 SCAR=6.9
Pod documented
401 181 my $self = shift;
402 181 ▶ $self->{temp_vars} = shift || {};
Condition100%2/2
shift() || {}
l!l
27154
MC/DC100%1/1
shift() || {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
403 181 my $res = $self->_execute($self->{ast});
404 177 $self->{temp_vars} = {};
405 177 return +$res;
406 }
407  
408 # executes a block, eg a list of statements
409 9 ▶sub _exec_block {
Subroutine _exec_block: called CC=2 SCAR=6.9
410 9 my $self = shift;
411 # warn "Executing block: ". Dumper(\@_);
412 9 my $res;
413 9 foreach (@_){
414 18 $res = $self->_execute($_);
415 }
416 9 $res;
417 }
418  
419 # executes a multiplication
420 90 ▶sub _exec_mul {
Subroutine _exec_mul: called CC=2 SCAR=6.9
421 90 my $self = shift;
422 90 my $prod = 1;
423 90 foreach (@_){
424 180 $prod *= $self->_execute($_);
425 }
426 90 $prod;
427 }
428  
429 # executes an _assignment
430 6 ▶sub _exec_assignment {
Subroutine _exec_assignment: called CC=2 SCAR=7.6
431 6 my ($self, $lvalue, $rvalue) = @_;
432 6 ▶ if (!is_lvalue($lvalue)){
Branch: 1 branch
BranchTrueFalseTotal
unless (is_lvalue($lvalue)) 0 6 6
433 0 confess('Internal error: $lvalue is not a "variable" AST');
434 }
435 6 return $self->{variables}{$lvalue->[1]} = $self->_execute($rvalue);
436 }
437  
438  
439 my %builtin_dispatch_table = (
440 2 ▶ 'sqrt' => sub { sqrt $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
441 3 ▶ 'ceil' => sub { ceil $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
442 3 ▶ 'floor' => sub { floor $_[0]},
Subroutine __ANON__: called CC=1 SCAR=0.0
443 5 ▶ 'sin' => sub { sin $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
444 1 ▶ 'asin' => sub { asin $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
445 1 ▶ 'cos' => sub { cos $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
446 1 ▶ 'acos' => sub { acos $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
447 1 ▶ 'tan' => sub { tan $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
448 1 ▶ 'atan' => sub { atan $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
449 3 ▶ 'exp' => sub { exp $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
450 1 ▶ 'log' => sub { log $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
451 4 ▶ 'sinh' => sub { (exp($_[0]) - exp(-$_[0]))/2},
Subroutine __ANON__: called CC=1 SCAR=0.0
452 2 ▶ 'cosh' => sub { (exp($_[0]) + exp(-$_[0]))/2},
Subroutine __ANON__: called CC=1 SCAR=0.0
453 1 ▶ 'log10' => sub { log($_[0]) / log(10) },
Subroutine __ANON__: called CC=1 SCAR=0.0
454 1 ▶ 'log2' => sub { log($_[0]) / log(2) },
Subroutine __ANON__: called CC=1 SCAR=0.0
455 3 ▶ 'theta' => sub { $_[0] > 0 ? 1 : 0 },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] > 0 ? : 1 2 3
456 3 ▶ 'pi' => sub { 3.141592653589793 },
Subroutine __ANON__: called CC=1 SCAR=0.0
457 17 );
458  
459  
460 6 ▶sub set_function {
Subroutine set_function: called CC=1 SCAR=0.0
Pod documented
461 6 my ($self, $name, $func) = @_;
462  
463 6 $self->{_user_dispatch_table}->{$name} = $func;
464 }
465  
466 # executes a function call
467 43 ▶sub _exec_function_call {
Subroutine _exec_function_call: called CC=4 SCAR=13.9
468 43 my $self = shift;
469 43 my $name = shift;
470  
471 43 my %dispatch_table = %builtin_dispatch_table;
472  
473 43 ▶ my %user_fun = %{$self->{_user_dispatch_table} || {} };
Condition100%2/2
$self->{'_user_dispatch_table'} || {}
l!l
412
MC/DC100%1/1
$self->{'_user_dispatch_table'} || {}
$self->{'_user_dispatch_table'}
Truth table100%2/2
A
A= $self->{'_user_dispatch_table'}
Aresult
11
00
474 43 ▶ while (my ($k, $v) = each %user_fun) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %user_fun) 9 43 52
475 9 $dispatch_table{$k} = $v;
476 }
477  
478 43 ▶ if (my $fun = $dispatch_table{$name}){
Branch: 1 branch
BranchTrueFalseTotal
if (my $fun = $dispatch_table{$name}) { } 41 2 43
479 41 return $fun->(map {$self->_execute($_)} @_);
480 } else {
481 2 confess("Unknown function: $name");
482 }
483 }
484  
485 # checks if a variable is defined, and returns its value
486 31 ▶sub _variable_lookup {
Subroutine _variable_lookup: called CC=3 SCAR=11.0
487 31 my ($self, $var) = @_;
488 # warn "Looking up <$var>\n";
489 31 ▶ if (exists $self->{temp_vars}->{$var}){
Branch: 2 branches
BranchTrueFalseTotal
if (exists $self->{'temp_vars'}{$var}) { } 25 6 31
elsif (exists $self->{'variables'}{$var}) { } 3 3 6
490 25 return $self->{temp_vars}->{$var};
491 } elsif (exists $self->{variables}->{$var}){
492 3 return $self->{variables}->{$var};
493 } else {
494 3 $self->{var_callback}->($var);
495 }
496 }
497  
498 # used for testing purposes only:
499 # returns the (recursive) number of operands in the AST
500 308 ▶sub ast_size {
Subroutine ast_size: called CC=4 SCAR=13.9
Pod documented
501 308 my ($self, $ast) = @_;
502 308 ▶ $ast = defined $ast ? $ast : $self->{ast};
Branch: 1 branch
BranchTrueFalseTotal
defined $ast ? : 268 40 308
503 308 ▶ return 1 unless ref $ast;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ast 208 100 308
504 100 my $size = -1; # the initial op/type should be ignored
505 100 for (@$ast){
506 268 $size += $self->ast_size($_);
507 }
508 100 return $size;
509 }
510  
511 5 ▶sub variables {
Subroutine variables: called CC=4 SCAR=13.9
Pod documented
512 5 my ($self) = shift;
513 5 my %vars;
514 my $v;
515 5 my @todo = ($self->{ast});
516 5 ▶ while (@todo){
Branch: 1 branch
BranchTrueFalseTotal
if (@todo) 17 5 22
517 17 my $ast = shift @todo;
518 17 ▶ next unless ref $ast;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ast 5 12 17
519 12 ▶ if ($ast->[0] eq '$'){
Branch: 1 branch
BranchTrueFalseTotal
if ($ast->[0] eq '$') { } 8 4 12
520 8 $vars{$ast->[1]}++;
521 } else {
522 # XXX do we need push the first element of @$ast?
523 4 push @todo, @$ast;
524 }
525 }
526 5 return sort keys %vars;
527 }
528  
529 # emit perl code for an AST.
530 # needed for compiling an expression into a anonymous sub
531 261 ▶sub _ast_to_perl {
Subroutine _ast_to_perl: called CC=3 SCAR=11.0
532 261 my ($self, $ast) = @_;;
533 261 ▶ return $ast unless ref $ast;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ast 125 136 261
534  
535 544 ▶ my $joined_operator = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
536 544 my $op = shift;
537 63 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
538 63 join $op, map { '(' . $self->_ast_to_perl($_). ')' } @_
539 544 };
540 136 };
541  
542 my %translations = (
543 4 ▶ '$' => sub { qq/( exists \$vars{$_[0]} ? \$vars{$_[0]} : exists \$default_vars{$_[0]} ? \$default_vars{$_[0]} : \$self->{var_callback}->("$_[0]")) / },
Subroutine __ANON__: called CC=1 SCAR=0.0
544 4 ▶ '{' => sub { join "\n", map { $self->_ast_to_perl($_) . ";" } @_ },
Subroutine __ANON__: called CC=1 SCAR=0.0
545 2 ▶ '=' => sub { qq/\$vars{$_[0][1]} = / . $self->_ast_to_perl($_[1]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
546 '+' => &$joined_operator('+'),
547 '*' => &$joined_operator('*'),
548 '^' => &$joined_operator('**'),
549 '%' => &$joined_operator('%'),
550 10 ▶ '-' => sub { '-(' . $self->_ast_to_perl($_[0]) . ')' },
Subroutine __ANON__: called CC=1 SCAR=0.0
551 9 ▶ '/' => sub { '1/(' . $self->_ast_to_perl($_[0]) . ')' },
Subroutine __ANON__: called CC=1 SCAR=0.0
552 44 ▶ '&' => sub { $self->_function_to_perl(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
553 136 );
554 136 my ($action, @rest) = @$ast;
555 136 my $do = $translations{$action};
556 136 ▶ if ($do){
Branch: 1 branch
BranchTrueFalseTotal
if ($do) { } 136 0 136
557 136 return &$do(@rest);
558 } else {
559 0 confess "Internal error: don't know what to do with '$action'";
560 }
561 }
562  
563 {
564 my %builtins = (
565 2 ▶ sqrt => sub { "sqrt($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
566 3 ▶ ceil => sub { "ceil($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
567 3 ▶ floor => sub { "floor($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
568 5 ▶ sin => sub { "sin($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
569 1 ▶ asin => sub { "asin($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
570 1 ▶ cos => sub { "cos($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
571 1 ▶ acos => sub { "acos($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
572 1 ▶ tan => sub { "tan($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
573 1 ▶ atan => sub { "atan($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
574 3 ▶ exp => sub { "exp($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
575 1 ▶ log => sub { "log($_[0])" },
Subroutine __ANON__: called CC=1 SCAR=0.0
576 4 ▶ sinh => sub { "do { my \$t=$_[0]; (exp(\$t) - exp(-(\$t)))/2}" },
Subroutine __ANON__: called CC=1 SCAR=0.0
577 2 ▶ cosh => sub { "do { my \$t=$_[0]; (exp(\$t) + exp(-(\$t)))/2}" },
Subroutine __ANON__: called CC=1 SCAR=0.0
578 1 ▶ log10 => sub { "log($_[0]) / log(10)" },
Subroutine __ANON__: called CC=1 SCAR=0.0
579 1 ▶ log2 => sub { "log($_[0]) / log(2)" },
Subroutine __ANON__: called CC=1 SCAR=0.0
580 3 ▶ theta => sub { "$_[0] > 0 ? 1 : 0" },
Subroutine __ANON__: called CC=1 SCAR=0.0
581 3 ▶ pi => sub { "3.141592653589793" },
Subroutine __ANON__: called CC=1 SCAR=0.0
582 17 );
583  
584 44 ▶ sub _function_to_perl {
Subroutine _function_to_perl: called CC=3 SCAR=11.0
585 44 my ($self, $name, @args) = @_;
586 44 ▶ if ($self->{_user_dispatch_table}->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_user_dispatch_table"}{$name}) 7 37 44
587 return qq[\$user_functions{'$name'}->(]
588 7 . join(',', map { $self->_ast_to_perl($_) } @args)
589 . qq[)];
590 }
591 37 my $do = $builtins{$name};
592 37 ▶ if ($do){
Branch: 1 branch
BranchTrueFalseTotal
if ($do) { } 36 1 37
593 36 return $do->(map { $self->_ast_to_perl($_) } @args );
594 } else {
595 1 confess "Unknow function '$name'";
596 }
597 }
598 }
599  
600 17 ▶sub compiled {
Subroutine compiled: called CC=3 SCAR=11.0
Pod documented
601 73 my $self = shift;
602 73 local $Data::Dumper::Indent = 0;
603 73 local $Data::Dumper::Terse = 1;
604  
605 # the eval will close over %user_functions
606 # if it contains any calls to it. Closures FTW!
607 73 ▶ my %user_functions = %{ $self->{_user_dispatch_table} || {} };
Condition100%2/2
$self->{'_user_dispatch_table'} || {}
l!l
3835
MC/DC100%1/1
$self->{'_user_dispatch_table'} || {}
$self->{'_user_dispatch_table'}
Truth table100%2/2
A
A= $self->{'_user_dispatch_table'}
Aresult
11
00
608  
609 73 my $text = <<'CODE';
610 sub {
611 my %vars = %{; shift || {} };
612 use warnings FATAL => qw(uninitialized);
613 no warnings 'void';
614 my %default_vars = %{;
615 CODE
616 73 chomp $text;
617 73 $text .= Dumper($self->{variables}) . "};\n ";
618 73 $text .= $self->_ast_to_perl($self->{ast});
619 72 $text .= "\n}\n";
620 # print STDERR "\n$text";
621 72 ▶ my $res = eval $text;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
622 72 ▶ confess "Internal error while compiling: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 72 72
623 72 return $res;
624 }
625  
626 17 1;
627  
628 # vim: sw=4 ts=4 expandtab
« Evaluator/Util.pm ↑ Summary