Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignored tokens parsing (WIP) #14

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/commonTest/kotlin/me/alllex/parsus/Tests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -570,12 +570,45 @@ class Tests {
}
}

@Test
fun forceIgnoredTokenParsing() {
object : Grammar<SyntaxTree>() {
val ws by regexToken("\\s+", ignored = true)
val a by literalToken("a")
override val root by parser {
val a1 = lexeme(a)
ws()
val a2 = lexeme(a)
node(a1, a2)
}
}.run {
assertParsed("a a").isEqualTo(node(a.lex("a", 0), a.lex("a", 2)))
assertParsed(" a a ").isEqualTo(node(a.lex("a", 1), a.lex("a", 3)))
assertNotParsed("aa").failedWithTokenMismatch(ws, a, 1)
assertNotParsed(" aa").failedWithTokenMismatch(ws, a, 2)
}

object : Grammar<SyntaxTree>() {
val ws by regexToken("\\s+", ignored = true)
val a by literalToken("a")
override val root by parlex(a) and (-ws * parlex(a)) map { node(it.first, it.second) }
}.run {
assertParsed("a a").isEqualTo(node(a.lex("a", 0), a.lex("a", 2)))
assertParsed(" a a ").isEqualTo(node(a.lex("a", 1), a.lex("a", 3)))
assertNotParsed("aa").failedWithTokenMismatch(ws, a, 1)
assertNotParsed(" aa").failedWithTokenMismatch(ws, a, 2)
}
}

companion object {

private fun parlex(token: Token) = parser { lexeme(token) }

private fun <T> Grammar<T>.assertParsed(text: String): Assert<T> = assertThat(parseOrThrow(text))

private fun <T> Grammar<T>.assertNotParsed(text: String): Assert<ParseError> =
assertThat(parse(text)).isInstanceOf(ParseError::class)

private fun <T> Grammar<T>.assertThatParsing(text: String): Assert<ParseResult<T>> = assertThat(parse(text))

private fun node(vararg literals: LiteralToken, startOffset: Int = 0): Node {
Expand Down
Loading