nac3-spec/toy-impl/helper.py

25 lines
678 B
Python
Raw Normal View History

2020-12-22 16:53:33 +08:00
import ast
2020-12-23 10:34:56 +08:00
def quote_text(text):
return '\n'.join([f' {t}' for t in text.split('\n')])
2020-12-18 13:03:36 +08:00
class CustomError(Exception):
2020-12-22 16:53:33 +08:00
def __init__(self, msg, node = None):
2020-12-18 13:03:36 +08:00
self.msg = msg
2020-12-22 16:53:33 +08:00
if node is not None:
self.at(node)
def at(self, node):
self.msg = f'Error at {node.lineno}:{node.col_offset+1}-' \
f'{node.end_lineno}:{node.end_col_offset+1} ' \
2020-12-23 10:34:56 +08:00
f'\n{quote_text(ast.unparse(node))}\n{self.msg}'
2020-12-22 16:53:33 +08:00
return self
2020-12-18 13:03:36 +08:00
def stringify_subst(subst):
if isinstance(subst, str):
return subst
elements = [f"{key}: {str(value)}" for key, value in subst.items()]
return "{" + ', '.join(elements) + "}"
2020-12-22 16:53:33 +08:00