Implement manyUntil

This commit is contained in:
Florian Schroedl
2022-01-20 17:00:00 +01:00
parent 440077fb06
commit d4f4a8a4d7

View File

@@ -133,6 +133,14 @@ func ignore(parserFn: Parser -> ParserResult): (Parser -> ParserResult) {.inline
tokens: parser.tokens,
))
func manyUntil(acceptFn: Parser -> ParserResult, stopFn: Parser -> ParserResult): (Parser -> ParserResult) {.inline.} =
## Parse characters but throw success tokens away
return proc(parser: Parser): ParserResult =
var res: ParserResult = acceptFn(parser)
while res.isOk() and res.flatMap(stopFn).isErr():
res = res.flatMap(acceptFn)
return res
proc parseSeq(parser: ParserResult, xs: seq[Parser -> ParserResult]): ParserResult =
xs.foldl(a.flatMap(b), parser)
@@ -169,7 +177,7 @@ when isMainModule:
.parseSeq(@[
str("FOO"),
ignore(str("___")),
ignore(str("_")),
ch('B'),
ch('B'),
ch('A'),
ch('R'),
@@ -178,5 +186,20 @@ when isMainModule:
err => $err,
xs => xs.foldl(a & b.value, "")
)
# echo fooParser
echo fooParser
let manUntilTest = initParser("AAAB")
.flatMap(manyUntil(ch('B'), ch('B')))
echo initParser("**** Foo")
.parseSeq(@[
manyUntil(ch('*'), ch(' ')),
ignore(ch ' '),
str("Foo")
])
# echo initParser("AAAB").flatMap(ch 'b')
# # .flatMap(ch('A'))
# # .flatMap(ch('B'))
# .flatMap()
# echo manUntilTest