Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl -w
- # Brainfuck compiler by Norbert Bokor (glezmen@gmail.com)
- use strict;
- use bigint;
- use Term::ReadKey;
- die "Unknown parameter!\n" if ($#ARGV == 1 && $ARGV[1] ne "dbg");
- die "Usage: bfcompile.pl <brainfuck code> [dbg]\n" if ($#ARGV < 0 || $#ARGV > 1);
- my $SIZE = 30_000;
- my $INFLIMIT = 1e5;
- my $debug = 1 if ($#ARGV > 0);
- my @mem = map {0} (1 .. $SIZE);
- my $jto = my $cmds = my $ptr = my $stack = my $top = my $write = my $inf = 0;
- my $code = $ARGV[0];
- $code = join('',<F>) if (open F, "<$ARGV[0]");
- sub check($)
- {
- foreach (split('',shift))
- {
- ++$stack if (/\[/);
- --$stack if (/\]/);
- last if ($stack < 0);
- }
- die "ERROR: unmatched bracket!" if ($stack != 0);
- }
- sub run($)
- {
- open my $tty , '<', '/dev/tty';
- my @s = split('',shift);
- for ( my $i = 0; $i <= $#s ;)
- {
- $top = $ptr if ($ptr > $top);
- $_ = $s[$i];
- if ($stack > 0)
- {
- ++$stack if (/\[/);
- --$stack if (/\]/);
- if ($stack >= 0)
- {
- ++$i;
- next;
- }
- }
- elsif ($stack < 0)
- {
- ++$stack if (/\[/);
- --$stack if (/\]/);
- if ($stack < 0)
- {
- --$i;
- next;
- }
- else
- {
- die "ERROR: infinite loop? :S $inf loops jumping to pos $i" if ($i == $jto && $write == 0 && ++$inf > $INFLIMIT);
- $jto = $i;
- $write = 0;
- }
- }
- print "\nPTR: $ptr\tVAL: $mem[$ptr]\tTOP: $top\tPOS: $i\tTOTAL: $#s\tCMD: $_\tcommands: $cmds\n" if (defined $debug);
- ++$cmds if (/[-+,.<>\[\]]/);
- die "ERROR: pointer overrun!" if (/>/ && ++$ptr >= $SIZE);
- die "ERROR: pointer underrun!" if (/</ && --$ptr < 0);
- ReadMode "raw";
- $mem[$ptr] = ++$mem[$ptr] % 256 if (/\+/);
- $mem[$ptr] = ($mem[$ptr] + 255) % 256 if (/-/);
- print chr $mem[$ptr] if (/\./);
- $mem[$ptr] = ord(ReadKey(0, $tty)) if (/,/);
- ReadMode "normal";
- ++$write if (/[-+,<>]/);
- $stack = 1 if ($mem[$ptr] == 0 && /\[/);
- if (/\]/)
- {
- $stack = -1;
- --$i;
- }
- else
- {
- ++$i;
- }
- }
- print "\ncommands executed: $cmds\n";
- }
- check($code);
- run($code);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement