Skip to content

Strange syntax error only with zero '0' converted to int #88

@philip-h-dye

Description

@philip-h-dye

With this extremely simple grammar "1" succeeds but "0" fails. Can anyone shed light on this issue? Thanks

zero-fails.py

from prettyprinter import pprint as pp

from pegen.grammar_parser import GeneratedParser as GrammarParser
from pegen.utils import generate_parser, parse_string

grammar_spec = """
    start  : a=num

    num    : a=NUMBER { float(a.string) if '.' in a.string else int(a.string) }
"""

numbers = [ 1, 0 ]

for n in numbers :
    grammar = parse_string(grammar_spec, GrammarParser)
    # print() ; pp(grammar)
    grammar_parser_class = generate_parser(grammar)
    tree = parse_string(str(n), grammar_parser_class, verbose=True)
    verdict = 'PASSED' if tree is not None else 'FAILED'
    pp([ verdict, tree ]) ; print()

Output

start() ... (looking at 1.0: NUMBER:'1')
  num() ... (looking at 1.0: NUMBER:'1')
    number() ... (looking at 1.0: NUMBER:'1')
    ... number() -> TokenInfo(type=2 (NUMBER), string='1', start=(1, 0), end=(1, 1), line='1')
  ... num() -> 1
... start() -> 1
['PASSED', 1]

start() ... (looking at 1.0: NUMBER:'0')
  num() ... (looking at 1.0: NUMBER:'0')
    number() ... (looking at 1.0: NUMBER:'0')
    ... number() -> TokenInfo(type=2 (NUMBER), string='0', start=(1, 0), end=(1, 1), line='0')
  ... num() -> 0
... start() -> None
Traceback (most recent call last):
  File "/home/phdyex/src/python/grammar-tool/test-files/pegen/gunit/simple/issue/zero-syntax-error/./zero-fails.py", line 20, in <module>
    tree = parse_string(str(n), grammar_parser_class, verbose=True)
  File "/home/phdyex/.cache/pypoetry/virtualenvs/grammar-tool-srSGyud3-py3.10/lib/python3.10/site-packages/pegen/utils.py", line 66, in parse_string
    return run_parser(file, parser_class, verbose=verbose)  # type: ignore # typeshed issue #3515
  File "/home/phdyex/.cache/pypoetry/virtualenvs/grammar-tool-srSGyud3-py3.10/lib/python3.10/site-packages/pegen/utils.py", line 55, in run_parser
    raise parser.make_syntax_error("invalid syntax")
  File "<unknown>", line 1
    0
    ^
SyntaxError: invalid syntax

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions