SComb (su-ko-n-bu) is a simple but powerful parser combinator library written in Scala. SComb aims to replace scala-parser-combinators.
- primitive combinators
- string literal (
""
) - regular expression literal (
"".r
) - any character (wildcard) (
any
) - character set (
set(...)
)
- string literal (
rule
combinator- used in right-hand side of non-teriminal
- the other combinators
- zero or one (
e.?
) - zero or more (
e.*
) - one or more (
e.+
) - interleaving (
repead0By
,repeat1By
) - handling left-associativity (
chainl
) - methods to use for-comprehension (
map
,flatMap
filter
)
- zero or one (
- the combinators for better error reporting
commit
andwithErrorMessage
, to convert the failure to error parser
Add the following line to your build.sbt
libraryDependencies += "com.github.kmizu" %% "scomb" % "0.9.0"
You can write your own parser by inheriting
com.github.kmizu.scomb.SCombinator[T]
:
import com.github.kmizu.scomb.SCombinator
object IntegerParser extends SCombinator[Int] {
override def root: P[Int] = rule {
(digit.*).map{ case digits => digits.mkString.toInt }
}
lazy val digit: P[String] = set('0'to'9')
def main(args: Array[String]): Unit = {
assert(parse("100") == Success(100))
}
}
In this example, P[Int]
indicates that the parse result is Int
.
digit
defined using set
combinator matches one of character from [0-9]
. digit.*
matches the repetition
of digit
and the result is translated to Int
by map{ case digits => digits.mkString.toInt }
. Finally,
a rule must be enclosed by rule { ... }
combinator.
Some examples are below:
- CalculatorSpec
- Arithmetic Expression Parser
- JsonSpec
- JSON Parser
- RegularExpressionSpec
- (Basic) Regular Expression Parser
- PrimitiveSpec
- Tests of primitive combinators