This is an interesting thread.
I'm not sure how deep you want to "dig into" simplifying bf code,
so i don't know if this is of much benefit for you.
Maybe you even want to do something like that:
Code: Select all
Repeat apply (Rule 1 > Rule 2 > ... > Rule 8)
until (no rule changes the source)
Apply rules means to replace the left side of the rule with the right side:
"Rule n: left side => right side"
To simplify computational (nonsense) counters you may use something like these rules:
Code: Select all
Rule 0: "+"^256 ==> ""
Rule 1: exists m: <start of file> (">"^m | "<"^m) "[" <any expression 1> "]" <any expression 2> ==> <start of file> (">"^m | "<"^m) <any expression 2>
Rule 2: "[" <any expr 1> "]" "[" <any expr 2> "]" ==> "[" <any expr 1> "]"
Rule 3: ("><" | "<>") ==> ""
Rule 4: ("+"|"-")* "[-]" ==> "[-]"
Rule 5-8 needs:
for_all m in [1 : 255] :
<Exp1> ::= "[-]" ("+"^m) "[" <Exp2> "-" <Exp2> "]"
<Exp2> ::= <Exp2> "<" <Exp2> ">" <Exp2> | <Exp2> ">" <Exp2> "<" <Exp2> | <Exp2> <Exp2> | "[-]" | ""
Rule 5: if exists n, "[-]" ("+"^m) "[" (">"^n) "[-]" <M> "]" in Exp1: Exp1 ==> "[-]" ("+"^m) "["(">"^n) <M> "]" (">"^n) "[-]" ("<"^n)
Rule 6: if exists n, "[-]" ("+"^m) "[" ("<"^n) "[-]" <M> "]" in Exp1: Exp1 ==> "[-]" ("+"^m) "["(">"^n) <M> "]" (">"^n) "[-]" ("<"^n)
Rule 7, 8: analougous to Rules 5, and 6 but right side extraction
These rules are sketched only (using something like regular expressions and grammar in (some idiom) of BNF).
I hope you see how these rules should work, as i don't have the much time (these days...; sorry for that if not).
Example 1: The "delay" macro of the "hanoi.bf" file.
Code: Select all
[-]+++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++[>[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[>[-]+++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++[-]<-]<-]
Simplification result of example 1:
(Although in this case you can simplify to nothing, as these memory cells are never used uninitialized for other things.)
Example 2: Small bf program (just counts a little bit and finally displays "OK")
http://stackoverflow.com/questions/6853548/**censored**Code: Select all
++++++++[->-[->-[->-[-]<]<]<]>++++++++[<++++++++++>-]<[>+>+<<-]>-.>-----.>
Simplification result of example 2:
Code: Select all
>++++++++[<++++++++++>-]<[>+>+<<-]>-.>-----.>
But i fear there are multpiple additional rules to optimize bf code.
(You don't have to implement multiple simplification algorithm (snippets) as all simplifications
may be described using such rules.)
penpen