Im trying to parse a custom programming language using PLY in python, and im a bit confused
so for example, i want to parse
on create:
modifyProp relative width => 11
modifyProp height => 14
i want to make the on
part work like def
and then read the next part as an input (in this case create
, and then parse the :
like in python
i also want to make the modifyProp
part in the same way, with relative
being read as a parameter instead of an input if its included, and then reading =>
as a "change this to" command, then reading the integer
sorry if thats a bit confusing, any resources i could find were too confusing and i wasnt able to figure this out on my own, thanks in advanced if you can help
We want:
on create:
modifyProp relative width => 11
modifyProp height => 14
as str
ing and formatted in Python:
some_code_in_string = '''
def create(relative):
def modifyProp(relative):
return True if relative[0] >= 11 and relative[1] >= 14 else False
return modifyProp(relative)
print(create(relative))
'''
so that we can exec
ute some_code_in_string
:
exec(some_code_in_string, {'relative': [15, 20]})
Outputs:
True
Now if we have a
few lines of that code already in str
ing (which you might already have as a file), we can do something like:
def pythonicize(some_string):
some_new_string = ''
func_end = some_string.find(':')
func_start = True
index = func_end - 1
while not some_string[index:func_end].__contains__(' '):
index -= 1
func_start = index
some_new_string += 'def'
some_new_string += some_string[func_start:func_end]
some_new_string += '(relative):'
some_new_string += '\n'
some_new_string += '...'
return some_new_string
a = '''
on create:
modifyProp relative width => 11
modifyProp height => 14
'''
b = pythonicize(a)
print(b)
Outputs:
def create(relative):
...
I'm not really familiar with PLY language, I just got you started so you can finish writing the pythonicize
function as you see fit; there may be many edge cases (which I'm unfamiliar with) that you'd have to account for.