pythonpython-3.xparsinglexply

How to parse a function with ply in Python?


I'm trying to parse a custom programming language using PLY in Python, and I'm a bit confused.

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 it's included, and then reading => as a "change this to" command, then reading the integer.

How can I do that?


Solution

  • We want:

    on create:
      modifyProp relative width => 11
      modifyProp height => 14
    

    as string 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 execute 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 string (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.