| 1 | use strict; | ||
| 2 | |||
| 3 | package optimize::int; | ||
| 4 | |||
| 5 | use constant HINT_INTEGER => 0x00000001; | ||
| 6 | |||
| 7 | my @int_translate = qw(add subtract lt gt le ge eq ne ncmp negate preinc predec postinc postdec multiply divide modulo); | ||
| 8 | my @int_flags = qw(complement left_shift right_shift bit_and bit_xor bit_or); | ||
| 9 | my %int; | ||
| 10 | for(@int_translate) { | ||
| 11 | $int{$_} = "i_$_"; | ||
| 12 | } | ||
| 13 | for(@int_flags) { | ||
| 14 | $int{$_} = 0; | ||
| 15 | } | ||
| 16 | *old_op = *optimize::old_op; | ||
| 17 | *state = *optimize::state; | ||
| 18 | |||
| 19 | sub check { | ||
| 20 | my $class = shift; | ||
| 21 | my $op = shift; | ||
| 22 | my $mutate = 0; | ||
| 23 | if(exists($int{$op->name})) { | ||
| 24 | my $cv = $op->find_cv(); | ||
| 25 | if(exists($optimize::pads{$cv->ROOT->seq}) && | ||
| 26 | $optimize::pads{$cv->ROOT->seq}->[$op->targ]->[1]->{int}) { | ||
| 27 | $mutate++; | ||
| 28 | } elsif($op->can('first') && $op->first->name eq 'padsv' && | ||
| 29 | exists($optimize::pads{$cv->ROOT->seq}) && | ||
| 30 | $optimize::pads{$cv->ROOT->seq}->[$op->first->targ]->[1]->{int}) { | ||
| 31 | $mutate++; | ||
| 32 | } elsif($op->can('last') && $op->last->name eq 'padsv' && | ||
| 33 | exists($optimize::pads{$cv->ROOT->seq}) && | ||
| 34 | $optimize::pads{$cv->ROOT->seq}->[$op->last->targ]->[1]->{int}) { | ||
| 35 | $mutate++; | ||
| 36 | } | ||
| 37 | } | ||
| 38 | if($mutate && $int{$op->name}) { | ||
| 39 | $op->mutate($int{$op->name}); | ||
| 40 | $op->private($op->private | HINT_INTEGER); | ||
| 41 | } elsif($mutate) { | ||
| 42 | $op->private($op->private | HINT_INTEGER); | ||
| 43 | } | ||
| 44 | |||
| 45 | } | ||
| 46 | |||
| 47 | =head1 NAME | ||
| 48 | |||
| 49 | optimize::int - Turn on integer ops for specified variables | ||
| 50 | |||
| 51 | =head1 SYNOPSIS | ||
| 52 | |||
| 53 | use optimize; | ||
| 54 | my $int : optimize(int); | ||
| 55 | $int = 1.5; | ||
| 56 | $int += 1; | ||
| 57 | if($int == 2) { print "$int is integerized" } | ||
| 58 | |||
| 59 | =head1 DESCRIPTION | ||
| 60 | |||
| 61 | Most perl operators can be turned into integer versions which do | ||
| 62 | all work in integers and truncates (floors) all fractional | ||
| 63 | portions. This is traditionally done by C<use integer;> which turns | ||
| 64 | on integer operations in the scope. This is usually by far too wide | ||
| 65 | area to turn on those ops in. | ||
| 66 | |||
| 67 | For greater flexibility this allows you to turn on integer ops for a | ||
| 68 | specific variable using the optimize attribute with an int argument, | ||
| 69 | C<my $int : optimize(int);>. | ||
| 70 | |||
| 71 | =head1 AUTHOR | ||
| 72 | |||
| 73 | Artur Bergman E<lt>abergman@cpan.orgE<gt> | ||
| 74 | |||
| 75 | =head1 SEE ALSO | ||
| 76 | |||
| 77 | L<optimize> L<integer> | ||
| 78 | |||
| 79 | =cut | ||
| 80 |