Skip to content

Commit

Permalink
Merge pull request #179 from barnardb/matchMap
Browse files Browse the repository at this point in the history
Select the longest matching key in matchMap
  • Loading branch information
sirthias authored Jun 21, 2017
2 parents 2724867 + ecf2ea4 commit d7ad77a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
17 changes: 10 additions & 7 deletions parboiled-core/src/main/scala/org/parboiled2/Parser.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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._
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -670,4 +673,4 @@ object ParserMacros {

reify { ctx.Expr[RuleX](ruleTree).splice.asInstanceOf[Rule[I, O]] }
}
}
}
11 changes: 11 additions & 0 deletions parboiled-core/src/test/scala/org/parboiled2/BasicSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit d7ad77a

Please sign in to comment.