Skip to content

Instantly share code, notes, and snippets.

@WorryingWonton
Created May 29, 2018 23:40
Show Gist options
  • Select an option

  • Save WorryingWonton/179cc12f1e56bc6bbd1df4be26ce8a1d to your computer and use it in GitHub Desktop.

Select an option

Save WorryingWonton/179cc12f1e56bc6bbd1df4be26ce8a1d to your computer and use it in GitHub Desktop.
from lark import Transformer
cbat_grammar = """
?literal : string
| char
| array
| map
| int
| float
| boolean
array : "[" [literal ("," literal)*] "]"
map : "{" [kv_pair ("," kv_pair)*] "}"
kv_pair : literal ":" literal
string : ESCAPED_STRING
char : /'.'/
float : /-?[0-9]+.[0-9]*/
int : /-?[0-9]+/
boolean : /true|false/
%import common.ESCAPED_STRING
%import common.WS
%ignore WS
"""
class ASTElement():
pass
class IntLiteral(ASTElement):
def __init__(self, intx):
self.intx = intx
def to_rust_code(self):
return f'{self.intx}'
class FloatLiteral(ASTElement):
def __init__(self, floatx):
self.floatx = floatx
def to_rust_code(self):
return f'{self.floatx}'
class BoolLiteral(ASTElement):
def __init__(self, boolx):
self.boolx = boolx
def to_rust_code(self):
return f'{self.boolx}'
class CharLiteral(ASTElement):
def __init__(self, charx):
self.charx = charx
def to_rust_code(self):
return f'{self.charx}'
class StringLiteral(ASTElement):
def __init__(self, stringx):
self.stringx = stringx
def to_rust_code(self):
return f'{self.stringx}'
class ArrayLiteral(ASTElement):
def __init__(self, arrayx):
self.arrayx = arrayx
self.item_type = None
def to_rust_code(self):
if len(self.arrayx) > 0:
string = 'vec!['
count = 0
for elem in self.arrayx:
if count < len(self.arrayx) - 1:
string += elem.to_rust_code() + ', '
count += 1
else:
string += elem.to_rust_code()
return string + ']'
else:
return f'Vec::<{self.item_type}>::new()'
class MapLiteral(ASTElement):
def __init__(self, mapx):
self.mapx = mapx
def to_rust_code(self):
string = '{let mut m = BTreeMap::new();\n'
kv_index = 0
while kv_index < len(self.mapx):
string += f'm.insert({self.mapx[kv_index][0].to_rust_code()}, {self.mapx[kv_index][1].to_rust_code()});\n'
kv_index += 1
string += '}'
return string
class JTransformer(Transformer):
def int(self, int):
return IntLiteral(int[0].value)
def float(self, float):
return FloatLiteral(float[0].value)
def boolean(self, boolean):
return BoolLiteral(boolean[0].value)
def char(self, char):
return CharLiteral(char[0].value)
def string(self, string):
return StringLiteral(string[0].value)
def array(self, items):
return ArrayLiteral(items)
def map(self, items):
return MapLiteral([item.children for item in items])
# parser = Lark(cbat_grammar, start='literal')
# stuff = JTransformer().transform(parser.parse("[1, [2, [3], {3: [2, 2, 2], 5: 1}], true, false, \"Hello\", 'a', 1.2, 2.2222312312321]"))
# print(stuff.to_rust_code())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment