Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested IndentedBlock Issue when Implementing if/elif/else #417

Open
hfudev opened this issue Jun 21, 2022 · 1 comment
Open

Nested IndentedBlock Issue when Implementing if/elif/else #417

hfudev opened this issue Jun 21, 2022 · 1 comment

Comments

@hfudev
Copy link

hfudev commented Jun 21, 2022

Hi, I'm trying to implement the nested if/elif/else with IndentedBlock.

from pyparsing import (Forward, Group, IndentedBlock, Keyword, Opt,
                       SkipTo, Suppress, Word, alphas, ZeroOrMore)

STMT = Forward()
SUITE = IndentedBlock(STMT)

condition = SkipTo(':').set_results_name('condition') + Suppress(':')
if_decl = Keyword('if') + condition
elif_decl = Keyword('elif') + condition
else_decl = Keyword('else:')
if_ = Group(if_decl + SUITE)
elif_ = Group(elif_decl + SUITE)
else_ = Group(else_decl + SUITE)

CONDITIONAL = Group(if_ + ZeroOrMore(elif_) + Opt(else_))

STMT <<= CONDITIONAL | Word(alphas)

data = '''
if A:
    a
    if B:
        b
elif C:
    c
else:
    d
'''

STMT.parseString(data, parse_all=True).pprint()

The output is (Modified the format a bit, to make it more clear.)

[
    [
        ['if',
            'A',
            ['a', [
                ['if', 'B', ['b']],
                ['elif', 'C', ['c']],
                ['else:', ['d']]
            ]]
        ]
    ]
]

Seems like the inner if clause is wrongly parsed.

@hfudev
Copy link
Author

hfudev commented Jun 21, 2022

Just tested with a modified version of https://github.com/pyparsing/pyparsing/blob/master/examples/indented_block_example.py

data = """\
    A
        a
        b
        c
    B
        d
        b
            e
            f
        g
    C
        h
"""

group = pp.Forward()
group <<= pp.Group(pp.Char(pp.alphas) + pp.Group(pp.IndentedBlock(pp.Char(pp.alphas) | group)))

print(pp.OneOrMore(group).parseString(data))

The output is still not right. (modified the format a bit to make it clearer)

[
    ['A', [
        ['a', 'b', 'c']
    ]],
    ['B', [
        ['d', 'b']
    ]],
    ['e', [
        ['f']
    ]],
    ['g', [
        ['C']
    ]]
]

Seems like the weird behavior may relate to Forward?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant