Skip to content

Instantly share code, notes, and snippets.

@mbednarski
Created April 21, 2022 14:23
Show Gist options
  • Select an option

  • Save mbednarski/9e01e171cd2b7e4dd8127e7812965efa to your computer and use it in GitHub Desktop.

Select an option

Save mbednarski/9e01e171cd2b7e4dd8127e7812965efa to your computer and use it in GitHub Desktop.

Revisions

  1. mbednarski created this gist Apr 21, 2022.
    26 changes: 26 additions & 0 deletions plot_lark.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    from lark import Lark, tree
    from lark.visitors import CollapseAmbiguities
    import matplotlib.pyplot as plt

    def plot_trees(grammar:str, text:str, start='expr'):
    parser = Lark(grammar=grammar, start=start,ambiguity='explicit')
    parsed = parser.parse(text)
    trees = CollapseAmbiguities().transform(parsed)
    for t in trees:
    tree.pydot__tree_to_png(t, filename='tree.png', rankdir='TB')
    plt.figure(figsize=(8,8))
    plt.imshow(plt.imread("tree.png"))
    plt.show()

    grammar = r"""
    %import common.NUMBER
    %import common.WS
    BINARY_OP: "+" | "-" | "*" | "/"
    !expr : expr BINARY_OP expr
    | NUMBER
    %ignore WS
    """

    plot_trees(grammar, '9/3')