Skip to content

Instantly share code, notes, and snippets.

@dwarring
Last active December 20, 2015 11:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwarring/6127599 to your computer and use it in GitHub Desktop.
Save dwarring/6127599 to your computer and use it in GitHub Desktop.
perl6 brainf*ck program
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