70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
# IMPORTS
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
from __future__ import annotations;
|
|
from lark import Tree;
|
|
from typing import Generator;
|
|
from typing import List;
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
# GLOBALE KONSTANTEN
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
#
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
# KLASSE: Syntaxbaum
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
class SyntaxBaum(object):
|
|
expr: str;
|
|
kind: str;
|
|
children: List[SyntaxBaum];
|
|
tree: Tree;
|
|
|
|
def __init__(self, fml: Tree):
|
|
self.kind = fml.data;
|
|
if len(fml.children) == 1 and isinstance(fml.children[0], str):
|
|
self.expr = fml.children[0];
|
|
self.children = [];
|
|
self.tree = Tree(self.kind, fml.children);
|
|
else:
|
|
self.children = [ SyntaxBaum(child) for child in fml.children if isinstance(child, Tree) and child.data != 'symb' ];
|
|
self.tree = Tree(self.kind, [child.tree for child in self.children]);
|
|
signature_parts = [];
|
|
i = 0;
|
|
for subfml in fml.children:
|
|
if isinstance(subfml, str):
|
|
signature_parts.append(subfml);
|
|
elif subfml.data == 'symb':
|
|
symb = str(subfml.children[0]);
|
|
signature_parts.append(symb);
|
|
else:
|
|
signature_parts.append('{{{}}}'.format(i));
|
|
i += 1;
|
|
signature = ' '.join(signature_parts);
|
|
self.expr = signature.format(*self.children);
|
|
if self.kind in [ 'konj', 'konj_lang', 'disj', 'disj_lang', 'impl' ]:
|
|
lbrace = '(' if self.expr.startswith('(') else '( ';
|
|
rbrace = ')' if self.expr.endswith(')') else ' )';
|
|
self.expr = lbrace + self.expr + rbrace;
|
|
return;
|
|
|
|
def __str__(self):
|
|
return self.expr;
|
|
|
|
def __iter__(self) -> Generator[SyntaxBaum, None, None]:
|
|
for child in self.children:
|
|
yield child;
|
|
|
|
@property
|
|
def child(self) -> SyntaxBaum:
|
|
return self.children[0];
|
|
|
|
def pretty(self):
|
|
return self.tree.pretty(indent_str='- ');
|