Skip to content

ParserPEG with multiple root rules #88

Description

@Mortal

I have a grammar with multiple top-level non-terminals that I want to use at different points in my program. Currently I have to specify ONE root rule when loading a grammar with ParserPEG. That means I need to parse the same grammar multiple times with different root rule names if I want to use different root rules throughout my program.

Could Arpeggio add support for specifying the root rule name when calling parse(), instead of once and for all for the parser when instantiating it? Or is there another way of achieving this?

E.g. currently I have to do this:

from arpeggio.cleanpeg import ParserPEG

grammar = r"""
assignment = name "=" expr EOF
expression = expr EOF
name = r"\b[a-z]+\b"
expr = name (("+" / "-") name)*
"""
parser_e = ParserPEG(grammar, root_rule_name="expression")
parser_a = ParserPEG(grammar, root_rule_name="assignment")  # <-- BAD! Parsing the same grammar twice

def run(condition, action):
    parser_e.parse(condition)
    parser_a.parse(action)

run("a + b", "c = a + a + b")

I would like to be able to do this instead:

parser2 = ParserPEG(grammar)

def run2(condition, action):
    parser2.parse(condition, root_rule_name="expression")
    parser2.parse(action, root_rule_name="assignment")  # GOOD! One grammar, multiple root rules

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions