mathandy / svgpathtools

A collection of tools for manipulating and analyzing SVG Path objects and Bezier curves.
MIT License
557 stars 142 forks source link

adjust parsing to raise nicer exceptions #213

Open snoyer opened 1 year ago

snoyer commented 1 year ago

The current parsing works great on well formed path but could be improved when it comes to handling invalid cases:

  1. the "Unallowed implicit command" error message mentions an internal token index
  2. invalid tokens are silently dropped
  3. the parser can run out of tokens and let an IndexError: pop from empty list through
    
    Path('1,2')
    ValueError: Unallowed implicit command in 1,2, position -1

Path('M 100 100 L 200 200 Z 100 200') ValueError: Unallowed implicit command in M 100 100 L 200 200 Z 100 200, position 7

Path('M 0 1 L 0 0 L 0 0z1') ValueError: Unallowed implicit command in M 0 1 L 0 0 L 0 0z1, position 8

Path('M 1 2 3') IndexError: pop from empty list

Path('M 0 1 N 2 3') Path(Line(start=1j, end=(2+3j)))

Path('M 0 1 C 1 2 3 4\n 5 foo') IndexError: pop from empty list


This PR catches cases 2. and 3. and raises a standard `SyntaxError` highlighting the error location in the `d` string in all 3 cases:

Path('1,2') File "", line 1 1,2 ^ SyntaxError: missing command

Path('M 100 100 L 200 200 Z 100 200') File "", line 1 M 100 100 L 200 200 Z 100 200 ^^^ SyntaxError: missing command

Path('M 0 1 L 0 0 L 0 0z1') File "", line 1 M 0 1 L 0 0 L 0 0z1 ^ SyntaxError: missing command

Path('M 1 2 3') File "", line 1 M 1 2 3 ^ SyntaxError: not enough arguments

Path('M 0 1 N 2 3') File "", line 1 M 0 1 N 2 3 ^^^ SyntaxError: invalid token ' N '

Path('M 0 1 C 1 2 3 4\n 5 foo') File "", line 2 5 foo ^^^^ SyntaxError: invalid token ' foo'