Skip to content

Commit

Permalink
Fix separated and split combinator implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
alllex committed Dec 19, 2023
1 parent d068e10 commit f2de186
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/commonMain/kotlin/me/alllex/parsus/parser/parsers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ suspend fun <T : Any> ParsingScope.split(

val values = mutableListOf<T>()
values += if (!allowEmpty) term() else poll(term) ?: return emptyList()
while (true) {
poll(separator) ?: break
values += if (!trailingSeparator) term() else (poll(term) ?: break)
values += repeat(ignored(separator) * term, atLeast = 0)
if (trailingSeparator) {
poll(separator)
}
return values
}
Expand Down
23 changes: 23 additions & 0 deletions src/commonTest/kotlin/me/alllex/parsus/Tests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,29 @@ class Tests {
assertParsed("a,a").isEqualTo(node(a.lex(0), a.lex(2)))
assertParsed("a,a,").isEqualTo(node(a.lex(0), a.lex(2)))
}

object : Grammar<SyntaxTree>() {
val com by literalToken(",")
val a by literalToken("a")
val b by literalToken("b")
val ap by parser { lexeme(a) }
val bp by parser { lexeme(b) }
override val root by separated(ap, com) * -com * bp map { (a, b) -> node(a + b) }
}.run {
assertParsed("a,b").isEqualTo(node(a.lex(0), b.lex(2)))
assertParsed("a,a,b").isEqualTo(node(a.lex(0), a.lex(2), b.lex(4)))
}

object : Grammar<SyntaxTree>() {
val com by literalToken(",")
val a by literalToken("a")
val b by literalToken("b")
val ap by parser { lexeme(a) }
val bp by parser { lexeme(b) }
override val root by separated(ap, com, trailingSeparator = true) * -com * bp map { (a, b) -> node(a + b) }
}.run {
assertParsed("a,,b").isEqualTo(node(a.lex(0), b.lex(3)))
}
}

}

0 comments on commit f2de186

Please sign in to comment.