Skip to content

Instantly share code, notes, and snippets.

@crowsonkb
Created June 2, 2018 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crowsonkb/a325ce22013d820e97be9e0c54fdc31b to your computer and use it in GitHub Desktop.
Save crowsonkb/a325ce22013d820e97be9e0c54fdc31b to your computer and use it in GitHub Desktop.
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)
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