From 1f37861e2d4470e551caf55f87993397b3cea2d6 Mon Sep 17 00:00:00 2001 From: Anton Ekblad Date: Fri, 30 Sep 2022 20:33:41 +0200 Subject: [PATCH] Improved support for custom parser state. --- README.md | 2 +- build.gradle.kts | 2 +- .../kotlin/cc/ekblad/konbini/Parser.kt | 24 +++++++++++++++---- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 220cf29..83e4161 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ repositories { } dependencies { - implementation("cc.ekblad.konbini:konbini:0.1.1") + implementation("cc.ekblad.konbini:konbini:0.1.2") } ``` diff --git a/build.gradle.kts b/build.gradle.kts index b44e35c..6e2e69a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -12,7 +12,7 @@ plugins { } group = "cc.ekblad" -version = "0.1.1" +version = "0.1.2" repositories { mavenCentral() diff --git a/src/commonMain/kotlin/cc/ekblad/konbini/Parser.kt b/src/commonMain/kotlin/cc/ekblad/konbini/Parser.kt index 5b58460..2275b5d 100644 --- a/src/commonMain/kotlin/cc/ekblad/konbini/Parser.kt +++ b/src/commonMain/kotlin/cc/ekblad/konbini/Parser.kt @@ -26,8 +26,14 @@ sealed class ParserResult { * Applies the receiver parser to the given [input]. * If [skipWhitespace] is true, any whitespace at the beginning of the input is skipped. */ -fun Parser.parse(input: String, skipWhitespace: Boolean = false): ParserResult { - val state = ParserState().also { it.input = input } +fun Parser.parse(input: String, skipWhitespace: Boolean = false): ParserResult = + parse(input, skipWhitespace, ParserState()) + +/** + * Like [parse], but with a custom parser state. + */ +fun Parser.parse(input: String, skipWhitespace: Boolean = false, state: S): ParserResult { + state.input = input return try { val p = if (skipWhitespace) { parser { whitespace() ; this@parse() } @@ -47,7 +53,17 @@ fun Parser.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 Parser.parseToEnd(input: String, ignoreWhitespace: Boolean = false): ParserResult { +fun Parser.parseToEnd(input: String, ignoreWhitespace: Boolean = false): ParserResult = + parseToEnd(input, ignoreWhitespace, ParserState()) + +/** + * Like [parseToEnd], but with a custom parser state. + */ +fun Parser.parseToEnd( + input: String, + ignoreWhitespace: Boolean = false, + state: S +): ParserResult { val p = parser { val result = this@parseToEnd() if (ignoreWhitespace) { @@ -56,5 +72,5 @@ fun Parser.parseToEnd(input: String, ignoreWhitespace: Boolean = false): eof() result } - return p.parse(input, ignoreWhitespace) + return p.parse(input, ignoreWhitespace, state) }