14 shift if UNIVERSAL::isa($_[0], 'Imager::Expr');
24 my %default_constants =
26 # too many digits, better than too few
27 pi=>3.14159265358979323846264338327950288419716939937510582097494
31 my ($class, $opts) = @_;
33 # possibly this is a very bad idea
34 my ($type) = grep exists $expr_types{$_}, keys %$opts;
35 die "Imager::Expr: No known expression type"
37 my $self = bless {}, $expr_types{$type};
38 $self->{variables} = [ @{$opts->{variables}} ];
39 $self->{constants} = { %default_constants, %{$opts->{constants} || {}} };
40 $self->{ops} = $self->compile($opts->{$type}, $opts)
44 $self->{code} = $self->assemble()
50 my ($pack, $name) = @_;
51 $expr_types{$name} = $pack;
55 my ($class, $name) = @_;
61 return @{$_[0]->{variables}};
69 return $_[0]->{nregs};
73 return $_[0]->{cregs};
76 my $numre = '[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?';
86 my @ops = @{$self->{ops}};
88 # this function cannot current handle code with jumps
89 return 1 if grep $_->[0] =~ /^jump/, @ops;
91 # optimization - common sub-expression elimination
92 # it's possible to fold this into the code generation - but it will wait
94 my $max_opr = $Imager::Regops::MaxOperands;
95 my $attr = \%Imager::Regops::Attr;
104 my $desc = join(",", @{$op}[0..$max_opr]);
108 my $new = $seen{$desc};
110 for my $reg (@{$op}[1..$max_opr]) {
111 $reg = $new if $reg eq $old;
117 $seen{$desc} = $op->[-1];
124 # reduce division by a constant to multiplication by a constant
125 if ($op->[0] eq 'div' && $op->[2] =~ /^r(\d+)/
126 && defined($self->{"nregs"}[$1])) {
127 my $newreg = @{$self->{"nregs"}};
128 push(@{$self->{"nregs"}}, 1.0/$self->{"nregs"}[$1]);
130 $op->[2] = 'r'.$newreg;
133 $self->{ops} = \@ops;
139 my $attr = \%Imager::Regops::Attr;
140 my $max_opr = $Imager::Regops::MaxOperands;
141 my @ops = @{$self->{ops}};
143 $op->[0] = $attr->{$op->[0]}{opcode};
144 for (@{$op}[1..$max_opr+1]) { s/^[rpj]// }
146 my $pack = $Imager::Regops::PackCode x (2+$Imager::Regops::MaxOperands);
148 return join("", ,map { pack($pack, @$_, ) } @ops);
151 # converts stack code to register code
153 my ($self, @st_ops) = @_;
156 my @vars = $self->_variables();
157 my @nregs = (0) x scalar(@vars);
159 my $attr = \%Imager::Regops::Attr;
162 my $max_opr = $Imager::Regops::MaxOperands;
163 @vars{@vars} = map { "r$_" } 0..$#vars;
168 # combining constants makes the optimization below work
169 if (exists $nregs{$_}) {
170 push(@regstack, $nregs{$_});
173 $nregs{$_} = "r".@nregs;
174 push(@regstack,"r".@nregs);
178 elsif (exists $vars{$_}) {
179 push(@regstack, $vars{$_});
181 elsif (exists $attr->{$_} && length $attr->{$_}{types}) {
182 if (@regstack < $attr->{$_}{parms}) {
183 error("Imager::transform2: stack underflow on $_");
186 my @parms = splice(@regstack, -$attr->{$_}{parms});
187 my $types = join("", map {substr($_,0,1)} @parms);
188 if ($types ne $attr->{$_}{types}) {
189 if (exists $attr->{$_.'p'} && $types eq $attr->{$_.'p'}{types}) {
193 error("Imager::transform2: Call to $_ with incorrect types");
198 if ($attr->{$_}{result} eq 'r') {
199 $result = "r".@nregs;
203 $result = "p".@cregs;
206 push(@regstack, $result);
207 push(@parms, "0") while @parms < $max_opr;
208 push(@ops, [ $_, @parms, $result ]);
209 #print "$result <- $_ @parms\n";
213 error("Imager::transform2: stack underflow with $_");
216 $names{$1} = pop(@regstack);
218 elsif (/^\@(\w+)$/) {
219 if (exists $names{$1}) {
220 push(@regstack, $names{$1});
223 error("Imager::Expr: unknown storage \@$1");
228 error("Imager::Expr: unknown operator $_");
232 if (@regstack != 1) {
233 error("stack must have only one item at end");
236 if ($regstack[0] !~ /^p/) {
237 error("you must have a color value at the top of the stack at end");
240 push(@ops, [ "ret", $regstack[0], (-1) x $max_opr ]);
242 $self->{"nregs"} = \@nregs;
243 $self->{"cregs"} = \@cregs;
250 for my $op (@{$_[0]->{ops}}) {
251 $result .= "@{$op}\n";
256 # unassembles the compiled code
259 my $code = $self->{"code"};
260 my $attr = \%Imager::Regops::Attr;
261 my @code = unpack("${Imager::Regops::PackCode}*", $code);
262 my %names = map { $attr->{$_}{opcode}, $_ } keys %Imager::Regops::Attr;
263 my @vars = $self->_variables();
266 while (my @op = splice(@code, 0, 2+$Imager::Regops::MaxOperands)) {
267 my $opcode = shift @op;
268 my $name = $names{$opcode};
270 $result .= "j$index: $name($opcode)";
271 my @types = split //, $attr->{$name}{types};
272 for my $parm (@types) {
274 $result .= " $parm$reg";
277 $result.= "($vars[$reg])";
279 elsif (defined $self->{"nregs"}[$reg]) {
280 $result .= "($self->{\"nregs\"}[$reg])";
285 $result .= " -> $attr->{$name}{result}$op[-1]"
286 if $attr->{$name}{result};
290 $result .= "unknown($opcode) @op\n";
298 package Imager::Expr::Postfix;
300 @ISA = qw(Imager::Expr);
302 Imager::Expr::Postfix->register_type('rpnexpr');
304 my %op_names = ( '+'=>'add', '-'=>'subtract', '*'=>'mult', '/' => 'div',
305 '%'=>'mod', '**'=>'pow' );
308 my ($self, $expr, $opts) = @_;
310 $expr =~ s/#.*//; # remove comments
311 my @st_ops = split ' ', $expr;
314 $_ = $op_names{$_} if exists $op_names{$_};
315 $_ = $self->{constants}{$_} if exists $self->{constants}{$_};
317 return $self->stack_to_reg(@st_ops);
320 package Imager::Expr::Infix;
323 @ISA = qw(Imager::Expr);
324 use Imager::Regops qw(%Attr $MaxOperands);
327 eval "use Parse::RecDescent;";
328 __PACKAGE__->register_type('expr') if !$@;
330 # I really prefer bottom-up parsers
331 my $grammar = <<'GRAMMAR';
333 code : assigns 'return' expr
334 { $return = [ @item[1,3] ] }
336 assigns : assign(s?) { $return = [ @{$item[1]} ] }
338 assign : identifier '=' expr ';'
339 { $return = [ @item[1,3] ] }
343 relation : addition (relstuff)(s?)
346 for my $op(@{$item[2]}) { $return = [ $op->[0], $return, $op->[1] ] }
350 relstuff : relop addition { $return = [ @item[1,2] ] }
352 relop : '<=' { $return = 'le' }
353 | '<' { $return = 'lt' }
354 | '==' { $return = 'eq' }
355 | '>=' { $return = 'ge' }
356 | '>' { $return = 'gt' }
357 | '!=' { $return = 'ne' }
359 addition : multiply (addstuff)(s?)
362 # for my $op(@{$item[2]}) { $return .= " @{$op}[1,0]"; }
363 for my $op(@{$item[2]}) { $return = [ $op->[0], $return, $op->[1] ] }
366 addstuff : addop multiply { $return = [ @item[1,2] ] }
367 addop : '+' { $return = 'add' }
368 | '-' { $return = 'subtract' }
370 multiply : power mulstuff(s?)
371 { $return = $item[1];
372 # for my $op(@{$item[2]}) { $return .= " @{$op}[1,0]"; }
373 for my $op(@{$item[2]}) { $return = [ $op->[0], $return, $op->[1] ] }
377 mulstuff : mulop power { $return = [ @item[1,2] ] }
378 mulop : '*' { $return = 'mult' }
379 | '/' { $return = 'div' }
380 | '%' { $return = 'mod' }
382 power : powstuff(s?) atom
385 for my $op(reverse @{$item[1]}) { $return = [ @{$op}[1,0], $return ] }
389 powstuff : atom powop { $return = [ @item[1,2] ] }
390 powop : '**' { $return = 'pow' }
392 atom: '(' expr ')' { $return = $item[2] }
393 | '-' atom { $return = [ uminus=>$item[2] ] }
398 number : /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/
400 exprlist : expr ',' exprlist { $return = [ $item[1], @{$item[3]} ] }
401 | expr { $return = [ $item[1] ] }
403 funccall : identifier '(' exprlist ')'
404 { $return = [ $item[1], @{$item[3]} ] }
406 identifier : /[^\W\d]\w*/ { $return = $item[1] }
414 $parser = Parse::RecDescent->new($grammar);
419 my ($self, $expr, $opts) = @_;
421 $parser = Parse::RecDescent->new($grammar);
423 my $optree = $parser->code($expr);
425 $self->error("Error in $expr\n");
429 @{$self->{inputs}}{$self->_variables} = ();
430 $self->{varregs} = {};
431 @{$self->{varregs}}{$self->_variables} = map { "r$_" } 0..$self->_variables-1;
432 $self->{"nregs"} = [ (undef) x $self->_variables ];
433 $self->{"cregs"} = [];
434 $self->{"lits"} = {};
437 # generate code for the assignments
438 for my $assign (@{$optree->[0]}) {
439 my ($varname, $tree) = @$assign;
440 if (exists $self->{inputs}{$varname}) {
441 $self->error("$varname is an input - you can't assign to it");
444 $self->{varregs}{$varname} = $self->gencode($tree);
447 # generate the final result
448 my $result = $self->gencode($optree->[1]);
449 if ($result !~ /^p\d+$/) {
450 $self->error("You must return a color value");
453 push(@{$self->{genops}}, [ 'ret', $result, (0) x $MaxOperands ])
460 return $self->{genops};
464 my ($self, $tree) = @_;
467 my ($op, @parms) = @$tree;
469 if (!exists $Attr{$op}) {
470 die "Unknown operator or function $op";
473 for my $subtree (@parms) {
474 $subtree = $self->gencode($subtree);
476 my $types = join("", map {substr($_,0,1)} @parms);
478 if (length($types) < length($Attr{$op}{types})) {
479 die "Too few parameters in call to $op";
481 if ($types ne $Attr{$op}{types}) {
482 # some alternate operators have the same name followed by p
484 if (exists $Attr{$opp} &&
485 $types eq $Attr{$opp}{types}) {
489 die "Call to $_ with incorrect types";
493 if ($Attr{$op}{result} eq 'r') {
494 $result = "r".@{$self->{nregs}};
495 push(@{$self->{nregs}}, undef);
498 $result = "p".@{$self->{cregs}};
499 push(@{$self->{cregs}}, undef);
501 push(@parms, "0") while @parms < $MaxOperands;
502 push(@{$self->{genops}}, [ $op, @parms, $result]);
505 elsif (exists $self->{varregs}{$tree}) {
506 return $self->{varregs}{$tree};
508 elsif ($tree =~ /^$numre$/ || exists $self->{constants}{$tree}) {
509 $tree = $self->{constants}{$tree} if exists $self->{constants}{$tree};
511 if (exists $self->{lits}{$tree}) {
512 return $self->{lits}{$tree};
514 my $reg = "r".@{$self->{nregs}};
515 push(@{$self->{nregs}}, $tree);
516 $self->{lits}{$tree} = $reg;
528 Imager::Expr - implements expression parsing and compilation for the
529 expression evaluation engine used by Imager::transform2()
533 my $code = Imager::Expr->new({rpnexpr=>$someexpr})
534 or die "Cannot compile $someexpr: ",Imager::Expr::error();
538 This module is used internally by the Imager::transform2() function.
539 You shouldn't have much need to use it directly, but you may want to
542 To create a new Imager::Expr object, call:
545 my $expr = Imager::Expr->new(\%options)
546 or die Imager::Expr::error();
548 You will need to set an expression value and you may set any of the
557 A hashref defining extra constants for expression parsing. The names
558 of the constants must be valid identifiers (/[^\W\d]\w*/) and the
559 values must be valid numeric constants (that Perl recognizes in
562 Imager::Expr may define it's own constants (currently just pi.)
568 A reference to an array of variable names. These are allocated
569 numeric registers starting from register zero.
575 By default you can define a C<rpnexpr> key (which emulates RPN) or
576 C<expr> (an infix expression). It's also possible to write other
577 expression parsers that will use other keys. Only one expression key
580 =head2 Instance methods
582 The Imager::Expr::error() method is used to retrieve the error if the
583 expression object cannot be created.
587 Imager::Expr provides only a few simple methods meant for external use:
593 =item Imager::Expr->type_registered($keyword)
595 Returns true if the given expression type is available. The parameter
596 is the key supplied to the new() method.
598 if (Imager::Expr->type_registered('expr')) {
599 # use infix expressions
604 Returns the compiled code.
608 Returns a reference to the array of numeric registers.
612 Returns a reference to the array of color registers.
614 =item $expr->dumpops()
616 Returns a string with the generated VM "machine code".
618 =item $expr->dumpcode()
620 Returns a string with the disassembled VM "machine code".
624 =head2 Creating a new parser
626 I'll write this one day.
628 Methods used by parsers:
634 This is the main method you'll need to implement in a parser. See the
635 existing parsers for a guide.
637 It's supplied the following parameters:
643 $expr - the expression to be parsed
647 $options - the options hash supplied to transform2.
651 Return an array ref of array refs containing opcodes and operands.
653 =item @vars = $self->_variables()
655 A list (not a reference) of the input variables. This should be used
656 to allocate as many registers as there are variable as input
659 =item $self->error($message)
661 Set the return value of Imager::Expr::error()
663 =item @ops = $self->stack_to_reg(@stack_ops)
665 Converts marginally parsed RPN to register code.
669 Called to convert op codes into byte code.
673 Returns a regular expression that matches floating point numbers.
677 Optimizes the assembly code, including attempting common subexpression
678 elimination and strength reducing division by a constant into
679 multiplication by a constant.
681 =item register_type()
683 Called by a new expression parser implementation to register itself,
686 YourClassName->register_type('type code');
688 where type code is the parameter that will accept the expression.
692 =head2 Future compatibility
694 Try to avoid doing your own optimization beyond literal folding - if
695 we add some sort of jump, the existing optimizer will need to be
696 rewritten, and any optimization you perform may well be broken too
697 (well, your code generation will probably be broken anyway <sigh>).