Permalink
Browse files

Merge pull request #179 from barnardb/matchMap

Select the longest matching key in matchMap
  • Loading branch information...
sirthias committed Jun 21, 2017
2 parents 2724867 + ecf2ea4 commit d7ad77a5077c5da27544e1fbedbe5f57a20416b7
@@ -18,6 +18,7 @@ package org.parboiled2
import scala.annotation.tailrec
import scala.collection.immutable.VectorBuilder
import scala.collection.mutable
import scala.util.{ Failure, Success, Try }
import scala.util.control.{ NonFatal, NoStackTrace }
import shapeless._
@@ -449,10 +450,11 @@ abstract class Parser(initialValueStackSize: Int = 16,
* THIS IS NOT PUBLIC API and might become hidden in future. Use only if you know what you are doing!
*/
def __matchMap(m: Map[String, Any]): Boolean = {
val keys = m.keysIterator
while (keys.hasNext) {
val prioritizedKeys = new mutable.PriorityQueue[String]()(Ordering.by(_.length))
prioritizedKeys ++= m.keysIterator
while (prioritizedKeys.nonEmpty) {
val mark = __saveState
val key = keys.next()
val key = prioritizedKeys.dequeue()
if (__matchString(key)) {
__push(m(key))
return true
@@ -465,12 +467,13 @@ abstract class Parser(initialValueStackSize: Int = 16,
* THIS IS NOT PUBLIC API and might become hidden in future. Use only if you know what you are doing!
*/
def __matchMapWrapped(m: Map[String, Any]): Boolean = {
val keys = m.keysIterator
val prioritizedKeys = new mutable.PriorityQueue[String]()(Ordering.by(_.length))
prioritizedKeys ++= m.keysIterator
val start = _cursor
try {
while (keys.hasNext) {
while (prioritizedKeys.nonEmpty) {
val mark = __saveState
val key = keys.next()
val key = prioritizedKeys.dequeue()
if (__matchStringWrapped(key)) {
__push(m(key))
return true
@@ -670,4 +673,4 @@ object ParserMacros {
reify { ctx.Expr[RuleX](ruleTree).splice.asInstanceOf[Rule[I, O]] }
}
}
}
@@ -168,6 +168,17 @@ class BasicSpec extends TestParserSpec {
"blue" must beMatchedWith(3)
"black" must beMismatched
}
"Map[String, T] with keys that prefix each other" in new TestParser1[Int] {
val map = Map("a" -> 1, "ab" -> 2, "abc" -> 3, "abcd" -> 4, "abcde" -> 5, "abcdef" -> 6)
def targetRule = rule { map ~ EOI }
"a" must beMatchedWith(1)
"ab" must beMatchedWith(2)
"abc" must beMatchedWith(3)
"abcd" must beMatchedWith(4)
"abcde" must beMatchedWith(5)
"abcdef" must beMatchedWith(6)
}
}
"The Parser" should {

0 comments on commit d7ad77a

Please sign in to comment.