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

WIP: add a more comfortable way of adding grammars #4

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

yv
Copy link
Contributor

@yv yv commented Sep 17, 2019

This uses the grammar compiler of the parsing module but adds a new mechanism of specifying grammars via a metaclass (rather than using a module as a container for a grammar), using a simple DSL for specifying grammar rules, and a simple mechanism for specifying a (bare-bones but usable) scanner that interacts with the grammar.

Using this, you can specify a grammar more succinctly as in

from parsing import Grammar, Precedence, Lr
from parsing.automaton import Spec
from parsing.ast import mktoken, print_ast

class SimpleGrammar(Grammar):
    pAddOp = Precedence.left()
    pMulOp = Precedence.left(before=pAddOp)
    add = mktoken('add', pAddOp, tokens='+ -')
    mul = mktoken('mul', pMulOp, tokens='* /')
    whitespace = '\s+|\n'
    IntValue = mktoken('IntValue', re='-?(:0|[1-9]\d*)', convert=int)

Nonterm = SimpleGrammar.nonterm_base()

class Expr(Nonterm):
    """
    %start
    %reduce Expr op=add Expr
    %reduce Expr op=mul Expr
    %reduce IntValue
    %reduce '(' Expr ')'
    """

and instead of repeatedly callling parser.token(...) you'd call SimpleGrammar.feed(text, parser) to invoke the scanner derived from the token declarations.

This is essentially a forward port of the yv/parsing fork to the mainline parsing repo. I haven't ported the tests yet, and one potentially controversial item that's yet to be ported is an addition to reduce that adds type and range attributes to the nonterminals where the reduction method returns None. This makes it easier to create sensible ASTs from simple grammar descriptions.

I've put "WIP" in the title to signify that there are things missing from a merge-able state, but that I'm already interested in opinions/comments on this.

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

Successfully merging this pull request may close these issues.

None yet

2 participants