-
Notifications
You must be signed in to change notification settings - Fork 2
/
TokenParserUtil.scala
29 lines (24 loc) · 986 Bytes
/
TokenParserUtil.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package org.gerweck.scala.util
import scala.jdk.CollectionConverters._
import scala.reflect.{ ClassTag, classTag }
import scala.util.parsing.combinator.syntactical.TokenParsers
import java.util.concurrent.ConcurrentHashMap
/** Mix-in utility code to assist with Parser development.
*
* @author Sarah Gerweck <sarah.a180@gmail.com>
*/
trait TokenParserUtil extends TokenParsers with ParserUtil {
private[this] val typeParsers = new ConcurrentHashMap[ClassTag[_ <: Elem], Parser[Elem]].asScala
/** A parser that matches elements of a given type. This is useful if you have
* a hierarchy of traits that extend from `Elem` and want to easily be able to
* match certain classes of tokens.
*/
final protected[this] def tpe[A <: Elem : ClassTag]: Parser[A] = {
val ct = classTag[A]
val p = typeParsers getOrElseUpdate (ct, {
val clzz = ct.runtimeClass
elem(clzz.getSimpleName, { clzz isInstance _ })
})
p.asInstanceOf[Parser[A]]
}
}