Skip to content

Instantly share code, notes, and snippets.

@brianhsu
Last active April 22, 2019 15:46
Show Gist options
  • Save brianhsu/7362574ef7f4c4c42e4cdd549d41e99c to your computer and use it in GitHub Desktop.
Save brianhsu/7362574ef7f4c4c42e4cdd549d41e99c to your computer and use it in GitHub Desktop.
import scala.util.parsing.combinator._
case class Anyline(x: String)
case class Comment(comment: String)
case class Index(mode: String)
case class Field(iden: String, dataType: String, data: Any)
case class Block(name: String, data: Any)
object MyParsers extends RegexParsers {
override val whiteSpace = """[ \t]+""".r
private val anything = "[^{}\n\r#]+".r
private val newline = "\\R".r
private val identifier = "[^{}\n\r#\\s]+".r
val blockIdent: Parser[String] = "[^{}\n\r#]+".r <~ rep(newline)
val block: Parser[Any] = blockIdent ~ opt(newline) ~ "{" ~ blockContent <~ "}" ~ rep(newline) ^^ toBlock
val anyline: Parser[Any] = anything <~ (comment | newline) ^^ Anyline
val comment: Parser[Any] = "#[^{}\n\r]+".r <~ newline ^^ Comment
val field: Parser[Any] = "field" ~> identifier ~ "type" ~ identifier ~ opt(newline) ~ "{" ~ blockContent <~ "}" ^^ toField
val blockContent: Parser[Any] = rep(field | block | comment | index | anyline | newline )
val index: Parser[Any] = "index" ~ ":" ~> anything <~ (opt(comment) | newline) ^^ Index
def parseIndex(x: String) = parseAll(index, x)
def parseField(x: String) = parseAll(field, x)
def parse(x: String) = parseAll(block, x)
def parseAnyline(x: String) = parseAll(anyline, x)
def parseBlock(filename: String) = {
import scala.io.Source
val content = Source.fromFile(filename).mkString
parseAll(block, content)
}
def toField(x: Any) = x match {
case (ident: String) ~ "type" ~ (dataType: String) ~ _ ~ "{" ~ (data: List[_]) => new Field(ident.trim, dataType, data.filter(_ != "\n"))
}
def toBlock(x: Any) = x match {
case (ident: String) ~ _ ~ "{" ~ (data: List[_]) => new Block(ident.trim, data.filter(_ != "\n"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment