Peter Schneider


MCT, MCSD.NET, MCAD.NET, MCDBA

News

Locations of visitors to this page

  

Austrian .NET Community

Brainfuck Compiler and Interpreter in Powershell

Surley some of you know the Brainfuck programming language... there are many compilers and interpreters around, yet I haven't found some for powershell... so here we go:

Powershell Brainfuck Interpreter:

param ($i)

$t = @{ '>'='$p++;';
'<'='$p--;';
'+'='$m[$p]++';
'-'='$m[$p]--';
'.'='write-host $([char]$m[$p]) -n ';
','='$m[$p]=$host.ui.ReadLine() ';
'['='while ($m[$p] -ne 0) {';
']'='}';
}

$c = '$p=0;$m=new-object "byte[]" 32768'+"`n" ; gc $i -Enc Byte -r 1 | % {$c+=$t["$([char]$_)"]+"`n"}

invoke-expression $c

Powershell Brainfuck Compiler:

param ( [string] $infile = $(throw "Please specify input file (.b)"),
[string] $outfile = $(throw "Please specify output file (.cs)"),
[switch] $run = $false
)

$csc = (join-path ($env:windir) Microsoft.NET\Framework\v2.0.50727\csc.exe)

$transpose = @{'>' = 'p++;';
'<' = 'p--;';
'+' = 'm[p]++;';
'-' = 'm[p]--;';
'.' = 'Console.Write(m[p]);';
',' = 'm[p]=Console.ReadLine();';
'[' = "while (m[p]!=0) {"
']' = '}';
}

$header = @"
using System;
public class Program {
public static void Main() {
int p=0;
char[] m=new char[32768];
"@

if ($(test-path $outfile)) { rm $outfile | out-null }
$header | out-file $outfile -append

get-content $infile -encoding Byte -readcount 1 |
% { $transpose["$([char]$_)"] } | out-file $outfile -append

"}}" | out-file $outfile -append

& $csc `/target:exe $outfile | out-null

if ($run) {
$outfile = $outfile.Replace(".cs",".exe")
& .`/$outfile
}

You can find the both script files (compiler and interpreter) in the attachment of this post.

Have fun!

Comments

Chris Martin said:

LOL. You're a freak dude!

# April 8, 2007 8:32 AM

Matthias Denkmaier said:

Ziemlich schräg aber gut! ;-)

# April 10, 2007 5:34 PM

lb said:

top work!

but surely, compiling it to C# like that is cheating?

isn't there a pure powershell way to write it?

# April 10, 2007 8:30 PM

pschneider said:

Hi lb!

The pure powershell way you see in the interpreter. A Compiler generates an executable - which is in this case done via C# ;-)

greetings, Peter

# April 11, 2007 4:12 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)