我不确定 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']]