view src/ploki/examples/bf2c.pk @ 8916:0234daffd946

<oerjan> addquote <int-e> I couldn\'t help thinking that maybe if one considers the ramifications in full detail it will turn out that overthinking is often not helpful and therefore, not something to be proud of.
author HackBot
date Sun, 14 Aug 2016 02:31:47 +0000
parents ac0403686959
children
line wrap: on
line source

#!/usr/local/bin/ploki
REM brainfuck to c translator

INSERT perl-util.pk HERE

LET tr("[") "while (*p) {\n"
LET tr("]") "}\n"
LET tr("<") "--p;\n"
LET tr(">") "++p;\n"
LET tr("+") "++*p;\n"
LET tr("-") "--*p;\n"
LET tr(".") "putchar(*p);\n"
LET tr(",") "*p = getchar();\n"
LET tr("0") "*p = 0;\n"

"#include <stdio.h>\nint main(void) {\nstatic unsigned char A[30000];\nunsigned char *p = A;\n" _ @s///g #<@clean @balanced @s///g #<@input \ARG:1 "'^[]<>.,+-'+" ""#> "'[]<>.,0+-'" @OMFG tr(\@)#> _ "return 0;\n}\n"
END

FOR clean LEET s \@
	LEET $c$ 0
	10 LET s @s///g #<@s///g #<s "{^|]!}[!'^[]'*]!" @OMFG @countrepl \0#> "{(^|]!)[!'^]'*}[!'^[]'*]!" @OMFG @countrepl \0#>
	IF $c$
		LET $c$ 0
		GOFOR 10
	FI
KTHX @s///g #<s "[!'+-']!" "0"#>

FOR countrepl LET $c$ += 1
KTHX \@

FOR balanced LEET s @s///g #<\@ "'^[]'+" ""#>
	LEET $c$ 0
	10 LET s @s///g #<s "[!]!" @OMFG @countrepl ""#>
	IF $c$
		LET $c$ 0
		GOFOR 10
	FI
	IF s ; ""
		IACS "\V\ARG:0: error: unbalanced brackets
	FI
KTHX \@

FOR input LEET fh
	IF @TYPE OF \@ : "nothing"
		LET fh \EING
	ELSE
		LET fh @LAPERS \@
		IF @NOT fh
			IACS "\V\ARG:0: \V\@: \V\!
		FI
	FI
KTHX fh . @NEG 1