Skip to content

Instantly share code, notes, and snippets.

@elliptic-shiho
Last active August 29, 2015 14:16
Show Gist options
  • Save elliptic-shiho/409bbbbbaf7f314d0a79 to your computer and use it in GitHub Desktop.
Save elliptic-shiho/409bbbbbaf7f314d0a79 to your computer and use it in GitHub Desktop.
package xyz.elliptic_shiho.ecalc.scala
import scala.util.parsing.combinator._
/**
* @author eshiho
*/
object EcalcParser extends RegexParsers {
def digit = "[0-9]+".r
def bindigit = "[01]+".r
def hexdigit = "[0-9a-fA-F]+".r
def number : Parser[Int] =
"0x" ~> hexdigit ^^ (Integer.parseInt(_, 16)) |
"0b" ~> bindigit ^^ (Integer.parseInt(_, 2)) |
digit ^^ (Integer.parseInt(_))
def factor = number | "(" ~> expr <~ ")"
def primary_term : Parser[Int] =
"~" ~> factor ^^ (~_) |
factor ~ rep(
"**" ~ factor
) ^^ {
case number ~ list => list.foldLeft(number) {
case (x, "**" ~ y) => {
var ret : Int = 1
for (n <- 1 to y) {
ret *= x
}
ret
}
}
};
def term : Parser[Int] = primary_term ~ rep(
"*" ~ primary_term |
"/" ~ primary_term |
"%" ~ primary_term
) ^^ {
case number ~ list => (number /: list) {
case (x, "*" ~ y) => x * y
case (x, "/" ~ y) => x / y
case (x, "%" ~ y) => x % y
}
}
def expr : Parser[Int] = term ~ rep(
"+" ~ term |
"-" ~ term |
"&" ~ term |
"|" ~ term |
"^" ~ term
) ^^ {
case number ~ list => list.foldLeft(number) {
case (x, "+" ~ y) => x + y
case (x, "-" ~ y) => x - y
case (x, "&" ~ y) => x & y
case (x, "|" ~ y) => x | y
case (x, "^" ~ y) => x ^ y
}
}
def parse (input : String) {
parseAll(expr, input) match {
case Success(data, next) => {
println(data)
};
case NoSuccess(error, next) => {
scala.sys.error(error)
}
};
}
}
object ecalc {
def main (args : Array[String]) {
EcalcParser.parse("(1+2)*3+4")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment