Created
May 29, 2018 23:41
-
-
Save WorryingWonton/42c5412847855c23c681b53fd54b0dfc to your computer and use it in GitHub Desktop.
This file contains hidden or 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 lark import Transformer, Lark | |
| 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 AtomicLiteral(ASTElement): | |
| def __init__(self, scalar): | |
| self.scalar = scalar | |
| def to_rust_code(self): | |
| return f'{self.scalar}' | |
| 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 AtomicLiteral(int[0].value) | |
| def float(self, float): | |
| return AtomicLiteral(float[0].value) | |
| def boolean(self, boolean): | |
| return AtomicLiteral(boolean[0].value) | |
| def char(self, char): | |
| return AtomicLiteral(char[0].value) | |
| def string(self, string): | |
| return AtomicLiteral(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