blob: 34695ef2ed16fec8600dbcef8611737bf1e51812 (
plain) (
blame)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
import scala.util.parsing.combinator._
import scala.util.parsing.combinator.syntactical.StandardTokenParsers
import scala.util.parsing.input._
import scala.util.parsing.syntax._
import scala.collection.mutable.HashMap
object Test {
def main(args: Array[String]): Unit = {
import grammars3._
val head = phrase(AnBnCn)
println(extractResult(head(new lexical.Scanner("a b c"))))
println(extractResult(head(new lexical.Scanner("a a b b c c"))))
println(extractResult(head(new lexical.Scanner("a a a b b b c c c"))))
println(extractResult(head(new lexical.Scanner("a a a a b b b b c c c c"))))
println(extractResult(head(new lexical.Scanner("a a a b b b b c c c c"))))
println(extractResult(head(new lexical.Scanner("a a a a b b b c c c c"))))
println(extractResult(head(new lexical.Scanner("a a a a b b b b c c c"))))
}
}
object grammars3 extends StandardTokenParsers with PackratParsers {
def extractResult(r: ParseResult[_]) = r match {
case Success(a,_) => a
case Failure(a,_) => a
case Error(a,_) => a
}
lexical.reserved ++= List("a","b", "c")
val a: PackratParser[Any] = memo("a")
val b: PackratParser[Any] = memo("b")
val c: PackratParser[Any] = memo("c")
val AnBnCn: PackratParser[Any] =
guard(repMany1(a,b) ~ not(b)) ~ rep1(a) ~ repMany1(b,c)// ^^{case x~y => x:::y}
private def repMany[T](p: => Parser[T], q: => Parser[T]): Parser[List[T]] =
( p~repMany(p,q)~q ^^ {case x~xs~y => x::xs:::(y::Nil)}
| success(Nil)
)
def repMany1[T](p: => Parser[T], q: => Parser[T]): Parser[List[T]] =
p~opt(repMany(p,q))~q ^^ {case x~Some(xs)~y => x::xs:::(y::Nil)}
}
|