Created
June 30, 2011 07:21
-
-
Save folone/1055793 to your computer and use it in GitHub Desktop.
Brainfuck Parser, using parser combinators
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
import scala.util.parsing.combinator._ | |
import scala.collection.mutable._ | |
object Bf extends Application { | |
private val data = ArrayBuffer[Char]() // TODO fill | |
private var pointer = 0 | |
private var in: String = "" | |
private var _init = false | |
private def getNextInput() = { | |
val result = in(0) | |
in = in.drop(0) | |
result | |
} | |
private def init (input: String) = { | |
in = input | |
_init = true | |
} | |
def execute(parsed: List[Any]) { | |
if (_init) | |
parsed.foreach { item => | |
item match { | |
case "+" => data(pointer) = (data(pointer) + 1).toChar | |
case "-" => data(pointer) = (data(pointer) - 1).toChar | |
case "<" => pointer = pointer - 1 | |
case ">" => pointer = pointer + 1 | |
case "." => println(data(pointer)) | |
case "," => data(pointer) = getNextInput() | |
case (cycle: List[Any]) => { | |
if (data(pointer) != 0) | |
execute(cycle) | |
} | |
} | |
} | |
} | |
override def main(args: Array[String]) = { | |
val parsed = BfParser.parseAll(BfParser.expr, args(0)).get | |
init(args(1)) | |
execute(parsed) | |
} | |
} | |
object BfParser extends JavaTokenParsers with Application { | |
def symbol : Parser[String] = "+" | "-" | "<" | ">" | "." | "," | |
def cycle : Parser[List[Any]] = "[" ~> expr <~ "]" | |
def expr : Parser[List[Any]] = rep(symbol | cycle) | |
override def main (args: Array[String]) { | |
println("input: " + args(0)) | |
println(parseAll(expr, args(0))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment