40 lines
1.4 KiB
Python
40 lines
1.4 KiB
Python
from lark import Lark
|
|
from lark.lexer import Token
|
|
from lark.tree import Branch
|
|
|
|
import re
|
|
|
|
def parse_string(token: Token):
|
|
if token.type == 'STRING':
|
|
string = token.value[1:-1]
|
|
string = re.sub(r"\\n","\n", string)
|
|
string = re.sub(r"\\t","\t", string)
|
|
string = re.sub(r"\\r","\r", string)
|
|
string = re.sub(r"\\(.)",r"\1", string)
|
|
return string
|
|
elif token.type == 'RAW_STRING':
|
|
string = token.value[1:-1]
|
|
return string
|
|
elif token.type == 'LONG_STRING':
|
|
string = re.match(re.compile(r"<<\s*(?P<terminator>[^\n]+)\n(.*)\n(?P=terminator)", re.MULTILINE + re.DOTALL),token.value)
|
|
assert string is not None
|
|
string = string.group(2)
|
|
return string
|
|
|
|
def process_patch(branch: Branch[Token]):
|
|
# First instruction is always file declaration
|
|
target_file = parse_string(branch.children[0].children[0]) # pyright: ignore[reportUnknownMemberType, reportArgumentType]
|
|
|
|
for inst in branch.children[1:]:
|
|
match inst.data:
|
|
case "insert":
|
|
print(f"Inserting {parse_string(inst.children[1])} at {inst.children[0]} in {target_file}")
|
|
|
|
if __name__ == '__main__':
|
|
lark = Lark.open('grammar.lark', rel_to=__file__)
|
|
|
|
with open('test.txt', 'r') as f:
|
|
result = lark.parse(f.read())
|
|
for patch in result.children:
|
|
process_patch(patch)
|