-
Notifications
You must be signed in to change notification settings - Fork 1
Home
Grampa is a library for Kotlin that allows to quickly and easily create a parser that can process input on bases of parsing expression grammars (PEG). The special thing about it is that no pre-processing phases like code generation are necessary, because the grammar can be defined directly in the form of Kotlin functions. This means that no external DSL needs to be learned and each IDE that can handle Kotlin code is supported.
Grampa is a further development of the popular parboiled v1 library and its fork grappa, which has not been maintained since around 2016. Unlike the aforementioned libraries, Grampa tries to keep the necessary byte-code manipulations as low as possible and easy to understand, so that a high code quality and maintainability is given. Its goal is also to be easy to integrate, which is achieved, among other things, by not having a code generation phase.
To define a grammar one simply has to extend the class AbstractGrammar
. In this class each function corresponds to a parsing rule of the PEG.
open class MyGrammar : AbstractGrammar<Unit>() {
override fun start() = oneOrMore(letter()) + eoi()
}
The second step is to instantiate the defined grammar class with the createGrammar()
extension function provided by Grampa. In this extension function, mutual dependencies among the rule functions are resolved, which would otherwise lead to an endless recursion or a stack overflow.
val myGrammar = MyGrammar::class.createGrammar()
In the last step the parser can be executed specifying the previously generated grammar.
val myParser: Parser<Unit> = Parser(myGrammar)
val result: ParseResult<Unit> = myParser.run("abc")
- A calculator that evaluates simple mathmatical expressions: examples/calculator
- A Json parser that creates a tree representation out of a Json: examples/json