Created
June 2, 2018 14:57
-
-
Save crowsonkb/a325ce22013d820e97be9e0c54fdc31b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pyparsing as pp | |
from pyparsing import pyparsing_common as ppc | |
from repl import repl | |
class Node: | |
def __init__(self, name, *args): | |
self.name = name | |
self.items = args | |
def __repr__(self): | |
return '{}({})'.format(self.name, ', '.join(repr(i) for i in self.items)) | |
string = pp.quotedString.copy() | |
string.setParseAction(lambda t: t[0][1:-1]) | |
atom = ppc.integer ^ ppc.fnumber | string | |
node = pp.Forward() | |
node <<= ppc.identifier + pp.Suppress('(') + pp.Optional(pp.delimitedList(atom | node)) + pp.Suppress(')') | |
node.setParseAction(lambda t: Node(*t)) | |
repl(node) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from prompt_toolkit import prompt | |
from prompt_toolkit.history import InMemoryHistory | |
from pyparsing import ParseBaseException | |
def sgr(*args): | |
return '\x1b[{}m'.format(';'.join(str(i) for i in args)) | |
def repl(parser): | |
parser.validate() | |
history = InMemoryHistory() | |
while True: | |
try: | |
s = prompt('> ', history=history) | |
result = parser.parseString(s, parseAll=True) | |
for item in result: | |
print(item) | |
except ParseBaseException as err: | |
print(f'{sgr(1, 31)}{err.__class__.__name__}{sgr(0)}: {err}') | |
except KeyboardInterrupt: | |
pass | |
except EOFError: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment