Skip to content

Instantly share code, notes, and snippets.

@HerringtonDarkholme
Last active August 29, 2015 14:06
Show Gist options
  • Save HerringtonDarkholme/64494283e44d2eebe4ae to your computer and use it in GitHub Desktop.
Save HerringtonDarkholme/64494283e44d2eebe4ae to your computer and use it in GitHub Desktop.
Parser Combinator requires every regex is initialized before usage
import scala.util.parsing.combinator._
import scala.util.matching.Regex.Match
import scala.util.matching.Regex
import scala.annotation.{switch, tailrec}
object T extends RegexParsers {
abstract class AbstractSelector[S <: AbstractSelector[S]]
class ComplexSelector(val combinator: Char, val x: CompoundSelector, val xs: ComplexSelector)
extends AbstractSelector[ComplexSelector]() {
override def toString = xs match {
case _: ComplexSelector => xs + combinator.toString + x
case _ => x.toString
}
}
case class CompoundSelector(tpe: String, simpleSelectors: List[SimpleSelector])
extends AbstractSelector[CompoundSelector] {
override def toString = tpe + simpleSelectors.mkString("")
}
class SimpleSelector extends AbstractSelector[SimpleSelector]
override def skipWhitespace = false
private final val Combinator = """\s*[+>~]\s*""".r ^^ {
case cmb => (cpx: ComplexSelector, cpd: CompoundSelector) =>
new ComplexSelector(cmb.trim.head, cpd, cpx)
}
private final val Whitespace = """\s+""".r ^^ {
case cmb => (cpx: ComplexSelector, cpd: CompoundSelector) =>
new ComplexSelector(' ', cpd, cpx)
}
private final val ComplexZero = CompoundParser ^^ {
case cpd =>
new ComplexSelector('\u0000', cpd, null)
}
def ComplexParser: Parser[ComplexSelector] =
chainl1(ComplexZero, CompoundParser, (Combinator|Whitespace))
def CompoundParser: Parser[CompoundSelector] = (ident|"*") ^^ {
case tpe =>
CompoundSelector(tpe, List())
}
private final val ident = "[0-9A-Za-z_-]+".r
def main(args: Array[String]): Unit =
println(ident.toString)
println(parseAll(ComplexParser, "div").get)
}
@HerringtonDarkholme
Copy link
Author

I got it.

https://github.com/scala/scala-parser-combinators/blob/master/src/main/scala/scala/util/parsing/combinator/Parsers.scala#L248

By implicit conversion, ident is a Parser[String], which has plenty of call by name parameter and ... say, null value filled val get stuffed into those method's apply closure (yes, tons of closure). So the val should be lifted up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment