Skip to content

Instantly share code, notes, and snippets.

@davesque
Last active March 23, 2018 03:37
Show Gist options
  • Save davesque/fdc275e3a579affef9b13c14be35831b to your computer and use it in GitHub Desktop.
Save davesque/fdc275e3a579affef9b13c14be35831b to your computer and use it in GitHub Desktop.
import parsimonious
parser = parsimonious.Grammar(r"""
type = tuple_type / basic_type
tuple_type = "(" type next_type* ")"
next_type = "," type
basic_type = base sub? arrlist?
base = alphas
sub = (digits "x" digits) / digits
arrlist = (const_arr / dynam_arr)+
const_arr = "[" digits "]"
dynam_arr = "[]"
alphas = ~"[a-z]+"
digits = ~"[0-9]+"
""")
uint = parser.parse('uint')
uint256 = parser.parse('uint256')
fixed128x19 = parser.parse('fixed128x19')
tup = parser.parse('(uint,bool,fixed128x19)')
nested_tup = parser.parse('(uint,bool,(fixed,address))')
class ABIType:
pass
class Tuple(ABIType):
def __init__(self, children):
self.children = children
def __str__(self):
return '({})'.format(
','.join(str(c) for c in self.children),
)
class Basic(ABIType):
def __init__(self, base, sub, arrlist):
self.base = base
self.sub = sub
self.arrlist = arrlist
def __str__(self):
return '{}{}{}'.format(
self.base.text,
self.sub.text,
self.arrlist.text,
)
def convert(node):
if node.expr_name == 'type':
return convert(node.children[0])
if node.expr_name == 'tuple_type':
left_paren, first, rest, right_paren = node
children = [convert(first)]
for comma, abi_type in rest.children:
children.append(convert(abi_type))
return Tuple(children)
if node.expr_name == 'basic_type':
base, sub, arrlist = node
return Basic(base, sub, arrlist)
raise ValueError('Unexpected node type "{}" encountered'.format(node.expr_name))
# Converts tup to a Tuple instance
converted_tup = convert(tup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment