Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Sources/Parsing/Parsers/Map.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ extension Parser {
@_disfavoredOverload
@inlinable
public func map<NewOutput>(
_ transform: @escaping (Output) -> NewOutput
_ transform: @escaping (Output) throws -> NewOutput
) -> Parsers.Map<Self, NewOutput> {
.init(upstream: self, transform: transform)
}
Expand All @@ -25,18 +25,18 @@ extension Parsers {
public let upstream: Upstream

/// The closure that transforms output from the upstream parser.
public let transform: (Upstream.Output) -> NewOutput
public let transform: (Upstream.Output) throws -> NewOutput

@inlinable
public init(upstream: Upstream, transform: @escaping (Upstream.Output) -> NewOutput) {
public init(upstream: Upstream, transform: @escaping (Upstream.Output) throws -> NewOutput) {
self.upstream = upstream
self.transform = transform
}

@inlinable
@inline(__always)
public func parse(_ input: inout Upstream.Input) rethrows -> NewOutput {
self.transform(try self.upstream.parse(&input))
public func parse(_ input: inout Upstream.Input) throws -> NewOutput {
try self.transform(self.upstream.parse(&input))
Comment on lines +38 to +39
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Losing rethrows is probably the main reason why we'd want a dedicated operator for a throwing map. Combine does the same thing with tryMap. We're definitely open to adding tryMap! Want to start a discussion about tryMap and other potential throwing operators?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've started one at #121.

}
}
}
12 changes: 12 additions & 0 deletions Tests/ParsingTests/MapTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ final class MapTests: XCTestCase {
XCTAssertEqual("42", try Int.parser().map(String.init).parse(&input))
XCTAssertEqual(" Hello, world!", Substring(input))
}

func testFail() {
enum MyError: String, Error, Equatable {
case fails
}

var input = "42 Hello, world!"[...].utf8
XCTAssertThrowsError(try Int.parser().map { _ in throw MyError.fails }.parse(&input)) { error in
XCTAssertEqual(error as? MyError, MyError.fails)
}
XCTAssertEqual(Substring(input), " Hello, world!"[...])
}

func testOverloadArray() {
let array = [1].map { "\($0)" }
Expand Down