Skip to content

Instantly share code, notes, and snippets.

@binarytemple
Created June 12, 2013 15:40
Show Gist options
  • Save binarytemple/5766468 to your computer and use it in GitHub Desktop.
Save binarytemple/5766468 to your computer and use it in GitHub Desktop.
Minimal Parboiled parser to parse Trapit query requests.
package com.zeebox.context.feedsingest.trapit
object QueryTermParser {
/**
* {{{
* A sample...
* "type:topic id:asddfasdsfafda Dessert"
* type A traps type: Bundle,Topic, or Source. String
* id GUID of the trap GUID
* }}}
*/
def apply() = {
new QueryTermParser()
}
}
import org.parboiled.scala._
import org.parboiled.errors.ParsingException
import org.parboiled.errors.ErrorUtils
class QueryTermParser extends Parser {
def OptionExpression = rule { optional(Expression) }
def Expression = rule { oneOrMore(Pair, " ") ~~> (_.toMap[String,String]) ~ optional(" " ~ SearchTerm) }
def Pair = rule { Term ~ ":" ~ Term }
def Term = rule { oneOrMore(noneOf(": ")) ~> (_.toString) }
def SearchTerm = rule { optional(oneOrMore(noneOf(""))) ~> (_.toString) }
}
object QueryTermParserMain {
def main(args: Array[String]) {
import org.parboiled.scala._
val qtp = new QueryTermParser {override val buildParseTree = true}
// System.err
// .println(ParseTreeUtils.printNodeTree(ReportingParseRunner(qtp.SearchTerm).run("asdfaad--90kl0-----fsadsf")))
// System.err.println(ParseTreeUtils.printNodeTree(ReportingParseRunner(qtp.Term).run("sdfadfasadfs-")))
//
// System.err.println(ParseTreeUtils.printNodeTree(ReportingParseRunner(qtp.OptionExpression).run("id:value")))
//
// System.err.println(ParseTreeUtils.printNodeTree(
// ReportingParseRunner(qtp.OptionExpression).run("type:topic id:asddfasdsfafda Dessert is nice to eat!!!")))
val run = RecoveringParseRunner(
qtp.OptionExpression, 1000).run("type:topic id:asddfasdsfafda Dessert is nice to eat!!!")
val option: Option[(Map[String, String], Option[String])] = run.result match {
case Some(astRoot) => astRoot
case None => throw new ParsingException("Invalid JSON source:\n" +
ErrorUtils.printParseErrors(run))
}
println(option)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment