Skip to content

Instantly share code, notes, and snippets.

@psiska
Created February 10, 2014 13:15
Show Gist options
  • Save psiska/8915705 to your computer and use it in GitHub Desktop.
Save psiska/8915705 to your computer and use it in GitHub Desktop.
Problem with Mustache parboiled2 parser
import org.parboiled2._
import scala.util.{ Success, Failure }
trait AST
case class AText(in: String) extends AST
case class AKey(in: String) extends AST
case class AEnd() extends AST
class MustacheParser(val input: ParserInput) extends Parser {
val openS = "{{"
val closeS = "}}"
def open: Rule0 = rule { str(openS) }
def close: Rule0 = rule { str(closeS) }
def deb(in: String) = rule { run(println(s"$in ch: ${cursorChar} + i: ${cursor}")) }
def NormalChar: Rule0 = rule { !(open | close) ~ deb("NC-b") ~ ANY ~ deb("NC-a") }
def debugKeyChar(prefix: String): Rule0 = rule { !(open | close ) ~ deb(s"$prefix-b") ~ ANY ~ deb(s"$prefix-a") }
def Characters: Rule0 = rule { zeroOrMore(NormalChar) } // word
def charsAST: Rule1[AST] = rule { capture(Characters) ~> ((s: String) => AText(s)) }
def charsKeyAST: Rule1[AST] = rule { capture(zeroOrMore(debugKeyChar("keyChar"))) ~> ((s: String) => AKey(s)) }
def KeyInner : Rule1[AST] = rule { open ~ charsKeyAST ~ close }
def Key: Rule1[AST] = rule {deb("tried key") ~ &(open) ~ deb("Key-b") ~ KeyInner ~ deb("Key-a") }
def rootRule: Rule1[Seq[AST]] = rule { zeroOrMore (Key | charsAST) ~ EOI}
}
object mymustache {
def main (args: Array[String]): Unit = {
val input1 = "asdasd XX asas"
val input2 = "abcdef {{XX}} ghij"
val input3 = "{{XX}}"
val input4 = "{{XX1}}{{XX2}}"
val parser = new MustacheParser(input3)
parser.rootRule.run() match {
case Success(a) => println("Expression is valid " + a)
case Failure(e: ParseError) ⇒ println("Expression is not valid: " + parser.formatError(e, showTraces = true))
case Failure(e) => println("Unexpected error during parsing run: " + e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment