| 1 | |||
| 2 | package Perlito5::FoldConstant; | ||
| 3 | |||
| 4 | use v5; | ||
| 5 | use Perlito5::AST; | ||
| 6 | use Perlito5::Dumper; | ||
| 7 | use strict; | ||
| 8 | |||
| 9 | sub fold_constant { | ||
| 10 | my $self = shift; | ||
| 11 | my $ref = ref($self); | ||
| 12 | return $self | ||
| 13 | if $ref eq 'Perlito5::AST::Int' | ||
| 14 | || $ref eq 'Perlito5::AST::Num' | ||
| 15 | || $ref eq 'Perlito5::AST::Buf'; | ||
| 16 | |||
| 17 | if ($ref eq 'Perlito5::AST::Apply' ) { | ||
| 18 | if ($self->{code} eq 'infix:<+>') { | ||
| 19 | my $arg0 = fold_constant($self->{arguments}[0]); | ||
| 20 | my $arg1 = fold_constant($self->{arguments}[1]); | ||
| 21 | if (is_constant($arg0) && is_constant($arg1)) { | ||
| 22 | my $v = $arg0->value + $arg1->value; | ||
| 23 | if ($v == int($v)) { | ||
| 24 | return Perlito5::AST::Int->new(int => $v); | ||
| 25 | } | ||
| 26 | return Perlito5::AST::Num->new(num => $v); | ||
| 27 | } | ||
| 28 | } | ||
| 29 | if ($self->{code} eq 'infix:<*>') { | ||
| 30 | my $arg0 = fold_constant($self->{arguments}[0]); | ||
| 31 | my $arg1 = fold_constant($self->{arguments}[1]); | ||
| 32 | if (is_constant($arg0) && is_constant($arg1)) { | ||
| 33 | my $v = $arg0->value * $arg1->value; | ||
| 34 | if ($v == int($v)) { | ||
| 35 | return Perlito5::AST::Int->new(int => $v); | ||
| 36 | } | ||
| 37 | return Perlito5::AST::Num->new(num => $v); | ||
| 38 | } | ||
| 39 | } | ||
| 40 | if ($self->{code} eq 'infix:<!=>') { | ||
| 41 | my $arg0 = fold_constant($self->{arguments}[0]); | ||
| 42 | my $arg1 = fold_constant($self->{arguments}[1]); | ||
| 43 | if (is_constant($arg0) && is_constant($arg1)) { | ||
| 44 | my $v = $arg0->value != $arg1->value; | ||
| 45 | if ($v) { | ||
| 46 | return Perlito5::AST::Int->new(int => 1); | ||
| 47 | } | ||
| 48 | return Perlito5::AST::Apply->UNDEF(); | ||
| 49 | } | ||
| 50 | } | ||
| 51 | if ($self->{code} eq 'prefix:<!>') { | ||
| 52 | my $arg0 = fold_constant($self->{arguments}[0]); | ||
| 53 | if (is_constant($arg0)) { | ||
| 54 | my $v = !$arg0->value; | ||
| 55 | if ($v) { | ||
| 56 | return Perlito5::AST::Int->new(int => 1); | ||
| 57 | } | ||
| 58 | return Perlito5::AST::Apply->UNDEF(); | ||
| 59 | } | ||
| 60 | } | ||
| 61 | |||
| 62 | if (my $const = $Perlito5::CONSTANT{ $self->{namespace} . '::' . $self->{code} }) { | ||
| 63 | return $const; | ||
| 64 | } | ||
| 65 | } | ||
| 66 | return $self; | ||
| 67 | } | ||
| 68 | |||
| 69 | sub is_constant { | ||
| 70 | my $self = shift; | ||
| 71 | my $ref = ref($self); | ||
| 72 | return $ref eq 'Perlito5::AST::Int' | ||
| 73 | || $ref eq 'Perlito5::AST::Num' | ||
| 74 | || $ref eq 'Perlito5::AST::Buf' | ||
| 75 | || ( $ref eq 'Perlito5::AST::Apply' && $self->{code} eq 'undef' ); | ||
| 76 | } | ||
| 77 | |||
| 78 | 1; | ||
| 79 |