Last active
December 20, 2015 11:59
-
-
Save dwarring/6127599 to your computer and use it in GitHub Desktop.
perl6 brainf*ck program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
grammar Brainfuck::Grammar { | |
rule TOP {^ [<cmd> || .+? ]* $} | |
proto token cmd { <...> } | |
token cmd:sym<ptr-inc> {\>} | |
token cmd:sym<ptr-dec> {\<} | |
token cmd:sym<inc> {\+} | |
token cmd:sym<dec> {\-} | |
token cmd:sym<input> {\,} | |
token cmd:sym<output> {\.} | |
token cmd:sym<loop> {\[} | |
token cmd:sym<end-loop> {\]} | |
} | |
class Brainfuck::Actions { ['sub offset($i) {$i > 0 ?? 2 * $i !! - (2 *$i) + 1};', | |
'my @mem', | |
'my $ptr = 0;', | |
'my $idx = 0;', | |
$<cmd>>>.ast ]; } | |
method cmd:sym<ptr-inc>($/) {make '$idx = offset(++$ptr);'} | |
method cmd:sym<ptr-dec>($/) {make '$idx = offset(--$ptr);'} | |
method cmd:sym<inc>($/) {make '++@mem[$idx];'} | |
method cmd:sym<dec>($/) {make '--@mem[$idx];'} | |
method cmd:sym<input>($/) {make '@mem[$idx] = $*IN.getc.ord;'} | |
method cmd:sym<output>($/) {make '$*OUT.print( @mem[$idx].chr );'} | |
method cmd:sym<loop>($/) {make 'while @mem[$idx] {'} | |
method cmd:sym<end-loop>($/) {make '}'} | |
} | |
Brainfuck::Grammar.parse($*IN.slurp, :actions(Brainfuck::Actions.new)); | |
EVAL $/.ast.join("\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment