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

Fix reported range when an optional parser is lifted to an AST parser #48

Merged
merged 1 commit into from
Oct 31, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import com.github.h0tk3y.betterParse.grammar.Grammar
import com.github.h0tk3y.betterParse.grammar.ParserReference
import com.github.h0tk3y.betterParse.lexer.Token
import com.github.h0tk3y.betterParse.lexer.TokenMatch
import com.github.h0tk3y.betterParse.parser.EmptyParser
import com.github.h0tk3y.betterParse.parser.Parser
import com.github.h0tk3y.betterParse.lexer.TokenMatchesSequence
import com.github.h0tk3y.betterParse.parser.*
import com.github.h0tk3y.betterParse.parser.ParsedValue

/** Encloses custom logic for transforming a [Parser] to a parser of [SyntaxTree].
* A correct implementation overrides [liftToSyntaxTree] so that it calls `recurse` for the sub-parsers, if any, and
Expand Down Expand Up @@ -108,9 +109,21 @@ private class ParserToSyntaxTreeLifter(
}

private fun <T> liftOptionalCombinatorToAST(combinator: OptionalCombinator<T>): Parser<SyntaxTree<T?>> {
val optionalLifted = optional(lift(combinator.parser))
return optionalLifted.map {
SyntaxTree(it?.item, listOfNotNull(it), combinator, it?.range ?: 0..0)
return object: Parser<SyntaxTree<T?>> {
override fun tryParse(tokens: TokenMatchesSequence, fromPosition: Int): ParseResult<SyntaxTree<T?>> {
val result = optional(lift(combinator.parser)).tryParse(tokens, fromPosition)
return when (result) {
is ErrorResult -> result
is Parsed -> {
val inputPosition = tokens[fromPosition]?.offset ?: 0
val ast = SyntaxTree(result.value?.item,
listOfNotNull(result.value),
combinator,
result.value?.range ?: inputPosition..inputPosition)
ParsedValue(ast, result.nextPosition)
}
}
}
}
}

Expand Down