Throwing errors from Parser.map
closure
#121
Replies: 2 comments
-
So a suggestion from @stephencelis was implementing a throwing Another option I've been implementing is a Verify {
Int.parser()
} check: { result in
guard result <= 42 else {
throw ParsingError.expectedInput("of less than 42")
}
} This could also be implemented as: Int.parser().verify { result in
guard result <= 42 else {
throw ParsingError.expectedInput("of less than 42")
}
} |
Beta Was this translation helpful? Give feedback.
-
I am also interested in a My use case is that I would like the concise Codable integration demonstrated by the Here are the extensions I am currently using. Nothing special, just the extension Parser {
func tryMap<NewOutput>(
_ transform: @escaping (Output) throws -> NewOutput
) -> Parsers.TryMap<Self, NewOutput> {
.init(upstream: self, transform: transform)
}
}
extension Parsers {
struct TryMap<Upstream: Parser, NewOutput>: Parser {
let upstream: Upstream
let transform: (Upstream.Output) throws -> NewOutput
init(
upstream: Upstream,
transform: @escaping (Upstream.Output) throws -> NewOutput
) {
self.upstream = upstream
self.transform = transform
}
func parse(_ input: inout Upstream.Input) throws -> NewOutput {
try self.transform(try self.upstream.parse(&input))
}
}
} Then I can do something like the following: extension MyDecodableType {
static func parser() -> Parsers.TryMap<Rest<Data>, Self> {
Rest()
.tryMap { try JSONDecoder().decode(Self.self, from: $0) }
}
} You could finesse that API, make the decoder injectable, etc, but that's the idea. |
Beta Was this translation helpful? Give feedback.
-
Working with the
throws
implementation, it would be useful to be able to check multiple input from a parse for extra details before allowing the parse to complete. For example, I have documentation like this that I'm parsing:I have a
FunctionDoc
structure I'm parsing the values into, and have the signature (first line) andParameters:
list parsed. Now, I want to check that the listed parameters actually match up to those in the signature.One option is
map
:Unfortunately, it doesn't allow
throw
in the transform function, so it's not much help. I chucked together a PR (which isn't merging, but is at #119 if you want to check it out) which addsthrows
to the signature. The main cost is that you have totry
whenever doing amap
.Open to other ideas. I looked a
filter
, but I don't like the error message it produces - it's very undescriptive. I'd rather throw my own error and have that output.Any thoughts?
Beta Was this translation helpful? Give feedback.
All reactions