benjamin-hodgson / Pidgin

A lightweight and fast parsing library for C#.
https://www.benjamin.pizza/Pidgin/
MIT License
883 stars 68 forks source link

A parser to recover from exceptions #144

Open eriksunsol opened 1 year ago

eriksunsol commented 1 year ago

I created CatchParser originally because I wanted to bail out from a delegate/lambda used with .Select() and be able to report sensible errors. I then found it to be a convenient means to bail out from deeply nested parsing, i.e. when using ExpressionParser and do common error handling and reporting on a higher level.

Before preparing this pull request I did however take a step back and achieved the same goal instead by letting errors detected deep down bubble up to higher level context by letting parsers return an error result instead of just failing. It turned out to work equally well or even better and make my code easier to follow as it does not skip out of deeply nested calls using try-catch.

With that said, I would generally recommend to design parsers so that they report errors or other events to outer contexts by returning results to represent such situations before resorting to using CatchParser. I can't think of any situation that could not be dealt with using what is already available in Pidgin using the strategy to basically never let a composition of nested parsers just fail but return a result representing the failure instead.

Nevertheless since I already wrote it and there may be use cases that I didn't think of, here it is. Feel free to accept or reject it.