Skip to content

mpe85/grampa

Repository files navigation

Grampa

A grammar parser library for Kotlin/JVM

Latest Release Maven Central Kotlin Build Coverage License

Grampa — short for Grammar parser — is a library that allows you to define grammars completely in Kotlin source code without any pre-processing phase (unlike other parser generators like ANTLR and JavaCC). Hence, there is no DSL to be learned, the whole grammar definition is in one place (a Kotlin class) and can be changed and maintained very easily. This library is inspired by parboiled v1 and grappa, but the focus is laid on simple and clean code without a lot of crazy and complicated byte code manipulation.

How to add to your build

Adding a dependency using Gradle (Groovy DSL):

repositories {
    mavenCentral()
}
dependencies {
    implementation 'com.github.mpe85:grampa:1.3.1'
}

Adding a dependency using Gradle (Kotlin DSL):

repositories {
    mavenCentral()
}
dependencies {
    implementation("com.github.mpe85:grampa:1.3.1")
}

Adding a dependency using Maven:

<dependency>
    <groupId>com.github.mpe85</groupId>
    <artifactId>grampa</artifactId>
    <version>1.3.1</version>
</dependency>

Adding a dependency using Ivy:

<dependency org="com.github.mpe85" name="grampa" rev="1.3.1"/>

Getting started

Create a grammar class by extending the AbstractGrammar class:

open class LetterGrammar : AbstractGrammar<Unit>() {
    override fun start() = oneOrMore(letter()) + eoi()
}

Instantiate the grammar by using the createGrammar extension function:

val grammar = LetterGrammar::class.createGrammar()

Run the parser using the created grammar:

val parser: Parser<Unit> = Parser(grammar)
val result: ParseResult<Unit> = parser.run("abc")

See the GitHub Wiki for a detailed documentation and examples.

Other Kotlin targets

Since this library relies on byte code manipulation using byte-buddy only the 'Kotlin/JVM' target is supported. Other Kotlin targets (like 'Kotlin/JS' or one of the various native targets) are unsupported.