Skip to content

Commit

Permalink
Improve error rendering in exception
Browse files Browse the repository at this point in the history
  • Loading branch information
alllex committed Oct 7, 2023
1 parent 7ccbde5 commit 97ef2a8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/commonMain/kotlin/me/alllex/parsus/parser/ParseResult.kt
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ data class UnmatchedToken(
override val contextProvider: ParseErrorContextProvider? = null
) : ParseError() {

override fun toString(): String = describe()

override fun describe(): String = format(
message = "Unmatched token at offset=$offset, when expected: $expected",
messageAtOffset = "Expected token: $expected"
Expand All @@ -77,6 +79,7 @@ data class MismatchedToken(
override val contextProvider: ParseErrorContextProvider? = null,
) : ParseError() {
override val offset: Int get() = found.offset
override fun toString(): String = describe()
override fun describe(): String = format(
message = "Mismatched token at offset=$offset, when expected: $expected, got: ${found.token}",
messageAtOffset = "Expected token: $expected at offset=$offset, got: ${found.token}"
Expand All @@ -86,25 +89,31 @@ data class MismatchedToken(
data class NoMatchingToken(
override val offset: Int,
) : ParseError() {

override fun toString(): String = describe()
override fun describe(): String = format(
message = "No matching token at offset=$offset",
messageAtOffset = "No matching token"
)
}

data class NoViableAlternative(
override val offset: Int,
) : ParseError() {
override fun toString(): String = describe()
override fun describe(): String = format(
message = "None of the alternatives succeeded at offset=$offset",
messageAtOffset = "None of the alternatives succeeded"
)
}

data class NotEnoughRepetition(override val offset: Int, val expectedAtLeast: Int, val actualCount: Int) : ParseError() {
override fun toString(): String = describe()
override fun describe(): String = "Expected at least $expectedAtLeast, found $actualCount"
}

class ParseException(val error: ParseError) : Exception() {
override fun toString(): String = "ParseException($error)"
override fun toString(): String = "ParseException: ${error.describe()}"
}

inline fun <T, R> ParseResult<T>.map(f: (T) -> R): ParseResult<R> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ internal class LastTokenMatchContext(
var lastMatch: TokenMatch? = null,
) : ParseErrorContextProvider {

override fun toString() = "LastTokenMatchContext(currentOffset=$currentOffset, lastMatch=$lastMatch)"

override fun getParseErrorContext(offset: Int): ParseErrorContext? {
if (offset != currentOffset) {
return null
Expand Down

0 comments on commit 97ef2a8

Please sign in to comment.