pointfreeco/swift-parsing

Using ParserPrinter+map in rawValue cause infinite loop

seongkue opened this issue · 0 comments

When enum type conform RawRepresentable, Swift use 'var rawValue' when compute equal operator( == )

enum SampleEnum: Equatable {
case a
case b
}

extension SampleEnum: RawRepresentable {
typealias RawValue = String
init?(rawValue: String) {
switch rawValue {
case "a": self = .a
case "b": self = .b
default: return nil
}
}
var rawValue: String {
print("rawValue called")
switch self {
case .a: return "a"
case .b: return "b"
}
}
}

let sampleA: SampleEnum = .a
let sampleB: SampleEnum = .b

print(sampleA == sampleB) // print "rawValue called"

So use ParserPrinter using "a".map { SampleEnum.a } in var rawValue { } cause infinite loop., because it called the method below.
extension Parsers.MapConstant: ParserPrinter where Upstream: ParserPrinter, Output: Equatable { @inlinable public func print(_ output: Output, into input: inout Upstream.Input) throws { guard output == self.output else { throw PrintingError.failed( summary: """ expected \(self.output) """, input: input ) } try self.upstream.print((), into: &input) } }

guard output == self.output --> call rawValue