Skip to content

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

Open
@hfudev

Description

@hfudev

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.

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