Build text parser

This commit is contained in:
Florian Schroedl
2022-01-20 17:00:00 +01:00
parent 647c5cdf00
commit 7c16ece752
8 changed files with 126 additions and 5 deletions

View File

@@ -78,6 +78,8 @@ func ch*(expectedChar: char): (Parser -> ParserResult) {.inline.} =
parser: parser,
))
let anyCh* = ch(AllChars)
func str*(s: string): (Parser -> ParserResult) {.inline.} =
return func(parser: Parser): ParserResult =
var p = parser.ok()
@@ -115,8 +117,8 @@ func manyUntil*(acceptFn: Parser -> ParserResult, stopFn: Parser -> ParserResult
res = res.flatMap(acceptFn)
return res
func anyUntil*(stopFn: Parser -> ParserResult): (Parser -> ParserResult) {.inline.} =
manyUntil(ch(AllChars), stopFn)
proc anyUntil*(stopFn: Parser -> ParserResult): (Parser -> ParserResult) {.inline.} =
manyUntil(anyCh, stopFn)
func choice*(parsers: seq[Parser -> ParserResult]): (Parser -> ParserResult) {.inline.} =
return proc(parser: Parser): ParserResult =

View File

@@ -155,6 +155,7 @@ proc applyParsersSeq*[T](
]]): BuilderResult[T] =
xs.foldl(a.flatMap((x: Builder[T]) => x.applyParsers(b[0], b[1])), builder)
proc foldBuilder*[T, T2](
builderResult: BuilderResult[T],
onError: string -> T2,

View File

@@ -19,3 +19,13 @@ proc initStringBuilder*(str: string): StringBuilderResult =
parser: initParser(str),
tree: newSeq[StringBuilderT](),
)))
proc fold*[T, E, T2](
self: Result[T, E],
onError: E -> T2,
onSuccess: T -> T2,
): T2 =
if self.isOk():
onSuccess(self.unsafeGet())
else:
onError(self.error())