Trying out larl parser

This commit is contained in:
2023-01-31 23:00:31 +02:00
parent df3c6d007a
commit 1acddb069f
19 changed files with 242 additions and 96 deletions

View File

@ -1,57 +1,21 @@
from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor
from rich import print
from .ebnf import ebnf
from mapper import *
from pathlib import Path
from lark import Lark
__all__ = ('ZiffersVisitor', 'parse_expression',)
grammar_path = Path(__file__).parent
grammar = grammar_path / "ziffers.lark"
GRAMMAR = Grammar(ebnf)
ziffers_parser = Lark.open(grammar, rel_to=__file__, start='value', parser='lalr', transformer=ZiffersTransformer())
class ZiffersVisitor(NodeVisitor):
"""
Visitor for the Ziffers syntax.
"""
def visit_ziffers(self, node, children):
"""
Top-level visiter. Will traverse and build something out of a complete and valid
Ziffers expression.
"""
print(f"Node: {node}, Children: {children}")
result = {'ziffers': []}
for i in children:
if i[0] in (None, [], {}) and isinstance(i[0], dict):
continue
try:
result['ziffers'].append(i[0])
except Exception as e:
print(f"[red]Error in ziffers:[/red] {e}")
pass
return result
def visit_pc(self, node, children):
return {node.expr_name: node.text}
def visit_escape(self, node, children):
return {node.expr_name: node.text}
# def visit_subdiv(self, node, visited_children):
#  key, values = visited_children
#  ret)rn {key, dict(values)}
def generic_visit(self, node, children):
"""
This method seem to be the generic method to include in any NodeVisitor.
Probably better to keep it as is for the moment. This is appending a whole
lot of garbage to the final expression because I don't really know how to
write it properly...
"""
return children or node
def parse_expression(expression: str) -> dict:
tree = GRAMMAR.parse(expression)
visitor = ZiffersVisitor()
return visitor.visit(tree)
def parse_expression(expr):
return ziffers_parser.parse(expr)
if __name__ == '__main__':
print(ziffers_parser.parse("[1 [2 3]]"))
#print(ziffers_parser.parse("(1 (1,3) 1..3)"))
#print(ziffers_parser.parse("_^ q _qe^3 qww_4 _123 <1 2>"))
#print(ziffers_parser.parse("q _2 _ 3 ^ 343"))
#print(ziffers_parser.parse("2 qe2 e4").values)
#print(ziffers_parser.parse("q 2 <3 343>"))
#print(ziffers_parser.parse("q (2 <3 343 (3 4)>)"))