From 51ec48bf05de2d4cb8020fad5435e958a9c513f9 Mon Sep 17 00:00:00 2001 From: Greenscreener Date: Sun, 20 Nov 2022 00:37:03 +0100 Subject: [PATCH] Added MJ's show function. --- formatitko.py | 6 +++--- mj_show.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 mj_show.py diff --git a/formatitko.py b/formatitko.py index e4b276f..6f45bae 100644 --- a/formatitko.py +++ b/formatitko.py @@ -5,10 +5,10 @@ from whitespace import * from panflute import * +from mj_show import show ifs = ["dog"] - def transform(e: Element): """Transform the AST, making format-agnostic changes.""" if isinstance(e, Whitespace) and bavlna(e): @@ -26,10 +26,10 @@ def transform(e: Element): doc = load() -print(stringify(doc)) +print(show(doc)) transform(doc) print("---------------------") -print(stringify(doc)) +print(show(doc)) print(vars(doc)) diff --git a/mj_show.py b/mj_show.py new file mode 100644 index 0000000..a02f2c1 --- /dev/null +++ b/mj_show.py @@ -0,0 +1,47 @@ +### +# For debugging, borrowed from here: git://git.ucw.cz/labsconf2022.git +### + +import sys, re +from panflute import * + +avoid_keys = { + 'dict', + 'list', + 'location', + 'oktypes', + 'parent', +} + +def show(e, file=sys.stdout, indent=""): + t = re.sub(r".*\.(.*)'>", r'\1', str(type(e))) + if isinstance(e, Str): + file.write(f'{indent}{t} "{e.text}"\n') + else: + file.write(f'{indent}{t}\n') + + if not isinstance(e, Str): + for k in e.__slots__: + if hasattr(e, k) and not k.startswith('_') and not k in avoid_keys: + file.write(f'{indent} {k}={getattr(e, k)}\n') + + if isinstance(e, Element): + children = sorted((child_name, getattr(e, child_name)) for child_name in e._children) + for name, c in children: + if name == 'content': + show(c, file, indent + ' ') + elif c is not None: + file.write(f'{indent} {name}=\n') + show(c, file, indent + ' ') + else: + file.write(f'{indent} {name}=None\n') + elif isinstance(e, ListContainer): + for c in e: + show(c, file, indent + ' ') + elif isinstance(e, DictContainer): + for name, c in e.items(): + file.write(f'{indent} {name}:\n') + show(c, file, indent + ' ') + else: + raise TypeError(type(e)) +