Created
April 2, 2024 23:31
-
-
Save kalloc/6d0aa8610c89d1a1be8e528eb2e73242 to your computer and use it in GitHub Desktop.
protoc-gen -decode parser
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 sys | |
import json | |
import re | |
import base58 as bs58 | |
from lark import Lark, Transformer | |
grammar = """ | |
?start: item+ | |
?item: pair | |
| object | |
| logs | |
| string | |
value: ESCAPED_STRING -> escaped | |
| SIGNED_NUMBER -> number | |
| string -> token | |
| "true" -> true | |
| "false" -> false | |
| "null" -> null | |
string: /[\w\d]+/ | |
object: string "{" item* "}" | |
pair: string ":" value | |
logs: "Logs" ":" value | |
%import common.ESCAPED_STRING | |
%import common.SIGNED_NUMBER | |
%import common.WS | |
%ignore WS | |
""" | |
class ParseToDict(Transformer): | |
def start(self, items): | |
return self._merge_dicts(items) | |
def pair(self, items): | |
key, value = items | |
return {key: value} | |
def object(self, items): | |
key, *values = items | |
return {key: self._merge_dicts(values)} | |
def logs(self, items): | |
return {"Logs": items[0].decode()} | |
def string(self, s): | |
(s,) = s | |
return str(s) | |
token = string | |
def escaped(self, s): | |
s = s[0][1:-1] | |
return s.encode("utf8").decode("unicode-escape").encode("latin1") | |
def number(self, n): | |
(n,) = n | |
return int(n) | |
def true(self, _): | |
return True | |
def false(self, _): | |
return False | |
def null(self, _): | |
return None | |
def _merge_dicts(self, dict_list): | |
merged = {} | |
for dictionary in dict_list: | |
for key, value in dictionary.items(): | |
if key in merged and isinstance(merged[key], list): | |
merged[key].append(value) | |
elif key in merged: | |
merged[key] = [merged[key], value] | |
else: | |
merged[key] = value | |
return merged | |
parser = Lark(grammar, start='start', parser='lalr', transformer=ParseToDict()) | |
def parse_input(input_text): | |
tree = parser.parse(input_text) | |
return tree | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
with open(sys.argv[1], 'r') as file: | |
input_data = file.read() | |
else: | |
input_data = sys.stdin.read() | |
result = parse_input(input_data) | |
def encode_bytes(val): | |
if isinstance(val, bytes): | |
return bs58.b58encode(val).decode() | |
return val | |
print(json.dumps(result, indent=2, default=encode_bytes)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test file:
Usage example: