Use string as error for ease of use
This commit is contained in:
24
src/test.nim
24
src/test.nim
@@ -28,8 +28,8 @@ type
|
||||
endOfStringErr
|
||||
ParserError = ref object
|
||||
kind: ParseErrorKind
|
||||
unexpected: char
|
||||
expected: char
|
||||
unexpected: string
|
||||
expected: string
|
||||
index: int
|
||||
parser: Parser
|
||||
ParserResult* = Result[Parser, ParserError]
|
||||
@@ -92,7 +92,7 @@ proc initParser(str: string): ParserResult =
|
||||
tokens: newSeq[Token](),
|
||||
).ok()
|
||||
|
||||
func ch(c1: char): (Parser -> ParserResult) {.inline.} =
|
||||
func ch(expectedChar: char): (Parser -> ParserResult) {.inline.} =
|
||||
return func(parser: Parser): ParserResult =
|
||||
let state = parser.state
|
||||
let newIndex = state.position + 1
|
||||
@@ -100,26 +100,26 @@ func ch(c1: char): (Parser -> ParserResult) {.inline.} =
|
||||
if newIndex > (state.stream.len - 1):
|
||||
return err(ParserError(
|
||||
kind: endOfStringErr,
|
||||
expected: c1,
|
||||
expected: &"{expectedChar}",
|
||||
index: newIndex,
|
||||
parser: parser,
|
||||
))
|
||||
else:
|
||||
let c2 = state.stream[newIndex]
|
||||
if c1 == c2:
|
||||
let foundChar = state.stream[newIndex]
|
||||
if expectedChar == foundChar:
|
||||
return Parser(
|
||||
state: ParserState(
|
||||
stream: state.stream,
|
||||
position: newIndex,
|
||||
lastPosition: parser.state.position,
|
||||
),
|
||||
tokens: parser.tokens & Token(value: c2)
|
||||
tokens: parser.tokens & Token(value: foundChar)
|
||||
).ok()
|
||||
else:
|
||||
return err(ParserError(
|
||||
kind: charMismatchErr,
|
||||
unexpected: c2,
|
||||
expected: c1,
|
||||
unexpected: &"{foundChar}",
|
||||
expected: &"{expectedChar}",
|
||||
index: newIndex,
|
||||
parser: parser,
|
||||
))
|
||||
@@ -165,11 +165,11 @@ proc foldTokens[T](
|
||||
onError(err)
|
||||
|
||||
when isMainModule:
|
||||
let fooParser = initParser("FOO_BAR")
|
||||
let fooParser = initParser("FOO___BAR")
|
||||
.parseSeq(@[
|
||||
str("FOO"),
|
||||
ignore(ch('_')),
|
||||
ch('B'),
|
||||
ignore(str("___")),
|
||||
ignore(str("_")),
|
||||
ch('B'),
|
||||
ch('A'),
|
||||
ch('R'),
|
||||
|
||||
Reference in New Issue
Block a user