Skip to content

Commit

Permalink
Improved support for custom parser state.
Browse files Browse the repository at this point in the history
  • Loading branch information
valderman committed Sep 30, 2022
1 parent 8fd3f25 commit 1f37861
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ repositories {
}

dependencies {
implementation("cc.ekblad.konbini:konbini:0.1.1")
implementation("cc.ekblad.konbini:konbini:0.1.2")
}
```

Expand Down
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ plugins {
}

group = "cc.ekblad"
version = "0.1.1"
version = "0.1.2"

repositories {
mavenCentral()
Expand Down
24 changes: 20 additions & 4 deletions src/commonMain/kotlin/cc/ekblad/konbini/Parser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,14 @@ sealed class ParserResult<in T> {
* Applies the receiver parser to the given [input].
* If [skipWhitespace] is true, any whitespace at the beginning of the input is skipped.
*/
fun <T> Parser<T>.parse(input: String, skipWhitespace: Boolean = false): ParserResult<T> {
val state = ParserState().also { it.input = input }
fun <T> Parser<T>.parse(input: String, skipWhitespace: Boolean = false): ParserResult<T> =
parse(input, skipWhitespace, ParserState())

/**
* Like [parse], but with a custom parser state.
*/
fun <S : ParserState, T> Parser<T>.parse(input: String, skipWhitespace: Boolean = false, state: S): ParserResult<T> {
state.input = input
return try {
val p = if (skipWhitespace) {
parser { whitespace() ; this@parse() }
Expand All @@ -47,7 +53,17 @@ fun <T> Parser<T>.parse(input: String, skipWhitespace: Boolean = false): ParserR
* Applies the receiver parser to the given [input].
* If [ignoreWhitespace] is true, any whitespace at the beginning or end of the input is ignored.
*/
fun <T> Parser<T>.parseToEnd(input: String, ignoreWhitespace: Boolean = false): ParserResult<T> {
fun <T> Parser<T>.parseToEnd(input: String, ignoreWhitespace: Boolean = false): ParserResult<T> =
parseToEnd(input, ignoreWhitespace, ParserState())

/**
* Like [parseToEnd], but with a custom parser state.
*/
fun <S : ParserState, T> Parser<T>.parseToEnd(
input: String,
ignoreWhitespace: Boolean = false,
state: S
): ParserResult<T> {
val p = parser {
val result = this@parseToEnd()
if (ignoreWhitespace) {
Expand All @@ -56,5 +72,5 @@ fun <T> Parser<T>.parseToEnd(input: String, ignoreWhitespace: Boolean = false):
eof()
result
}
return p.parse(input, ignoreWhitespace)
return p.parse(input, ignoreWhitespace, state)
}

0 comments on commit 1f37861

Please sign in to comment.