1

我想解析可以调用其他函数“返回”的函数的函数调用:

thisReturnsFunction()()

我已经这样做了:

id = Regex(r'[_a-zA-Z][_a-zA-Z0-9]*')

funcal = Forward()

value = funcal | id

funcal << value + Literal("(").suppress() + Literal(")").suppress()

不小心,Python 堆栈溢出,整个 Python 崩溃了。我知道value是递归的并且无限匹配,thisReturnsFunction("Hello!")因为funcal是匹配,因为value是数学,因为funcal是匹配......

如何避免这种情况并设计有效的模式?

4

1 回答 1

0

我不确定 Pyparsing 是否可以以“纯”方式解析高阶函数。但是有一些“hacky”方式:为函数创建标记,为标记添加处理程序并在处理程序中建立正确的语法结构。示例(我还为函数参数添加了标记)

from pyparsing import Forward, Literal, Regex, OneOrMore, Optional, Group, delimitedList

def function_parser(s, loc, toks):
    if len(toks) <= 2:
        return [toks[0], list(toks[1])]
    else:
        return [function_parser(s, loc, toks[:len(toks)-1]), toks[-1]]

id = Regex(r'[_a-zA-Z][_a-zA-Z0-9]*')
comma = Literal(',')
funcal = Forward()
expression  =  funcal | id 
function_args = Optional(Group(delimitedList(expression,comma)),[])
funcal << id + OneOrMore(Literal("(").suppress() + function_args + Literal(")").suppress())

funcal.setParseAction(function_parser)

def test_print(string):
    l = funcal.parseString(string).asList()
    print(l)

test_print('justFunction(arg)')
test_print('justFunction(arg)',)
test_print('thisReturnsFunction()()',)
test_print('thisReturnsFunction(arg1, arg2)(arg3)')

它产生:

['justFunction', ['arg']]
['justFunction', ['arg']]
[['thisReturnsFunction', []], []]
[['thisReturnsFunction', ['arg1', 'arg2']], ['arg3']]
于 2018-04-25T15:50:17.597 回答