parsial module

Python library that transforms any string parser into a parser that skips portions of the input that contain syntax errors.

parsial.parsial.parsial(parse: Callable[[str], Any]) Callable[[str], Tuple[Any, List[slice]]][source]

Accept a parsing function (that takes a string input) and return a new parsing function. This new function attempts to parse an input string using the original parsing function even if parsing errors occur. This is done by selectively removing portions of the input that cause errors.

>>> lines = [
...     'x = 123',
...     'y =',
...     'print(x)',
...     'z = x +',
...     'print(2 * x)'
... ]
>>> import ast
>>> parser = parsial(ast.parse)
>>> (a, slices) = parser('\n'.join(lines))
>>> exec(compile(a, '', 'exec'))
123
246

In addition to returning the result, the new function also returns a list of slice instances (one for each line found in the input string).

>>> for s in slices:
...     print(s)
slice(0, 7, None)
slice(0, 0, None)
slice(0, 8, None)
slice(0, 0, None)
slice(0, 12, None)

Each slice instance indicates what portion of the corresponding line in the input was included in the successful parsing attempt.

>>> [l[s] for (l, s) in zip(lines, slices)]
['x = 123', '', 'print(x)', '', 'print(2 * x)']

For a string that can be parsed successfully, the parser supplied to this function is invoked exactly once. In the worst case, it is invoked once per line of the input string.