使用Python在Lua文件中搜索所有函数调用

3
我希望使用Python搜索Lua文件中的所有函数调用。例如,我有以下Lua代码:
function displayText (text)
    print(text)
end

sendGreetings = function(sender, reciever) 
    print("Hi " ..reciever.. " greetings from " ..sender.. "!")
end

displayText("Hello, World!")

sendGreetings("Roger", "Michael")

我希望我的Python代码可以搜索其中的函数调用,并返回一个包含函数名称和参数的字典,因此输出应该像这样:
# {function_name: [param1, param2]}
{"displayText": ["Hello, World!"], "sendGreetings": ["Roger", "Michael"]}

我试图使用正则表达式来实现它,但是遇到了各种问题和不准确的结果。而且,我不认为有一个Python可以使用的Lua解析器。


2
你的 Lua 代码中被调用的函数是否总是只接受字符串参数? - Tim Biegeleisen
如果调用模式很简单,那么你可以使用我的 ltokenp 工具,在 https://web.tecgraf.puc-rio.br/~lhf/ftp/lua/#ltokenp 上获取。 - lhf
1个回答

2

您可以使用luaparserpip install luaparser)进行递归遍历ast

import luaparser
from luaparser import ast
class FunCalls:
   def __init__(self):
      self.f_defs, self.f_calls = [], []
   def lua_eval(self, tree):
      #attempts to produce a value for a function parameter. If value is a string or an integer, returns the corresponding Python object. If not, returns a string with the lua code
      if isinstance(tree, (luaparser.astnodes.Number, luaparser.astnodes.String)):
         return tree.n if hasattr(tree, 'n') else tree.s
      return ast.to_lua_source(tree)
   def walk(self, tree):
      to_walk = None
      if isinstance(tree, luaparser.astnodes.Function):
         self.f_defs.append((tree.name.id, [i.id for i in tree.args]))
         to_walk = tree.body
      elif isinstance(tree, luaparser.astnodes.Call):
         self.f_calls.append((tree.func.id, [self.lua_eval(i) for i in tree.args]))
      elif isinstance(tree, luaparser.astnodes.Assign):
         if isinstance(tree.values[0], luaparser.astnodes.AnonymousFunction):
            self.f_defs.append((tree.targets[0].id, [i.id for i in tree.values[0].args]))
      if to_walk is not None:
         for i in ([to_walk] if not isinstance(to_walk, list) else to_walk):
             self.walk(i)
      else:
         for a, b in getattr(tree, '__dict__', {}).items():
            if isinstance(b, list) or 'luaparser.astnodes' in str(b):
               for i in ([b] if not isinstance(b, list) else b):
                   self.walk(i)

将所有内容整合在一起:
s = """
function displayText (text)
   print(text)
end

sendGreetings = function(sender, reciever) 
   print("Hi " ..reciever.. " greetings from " ..sender.. "!")
end

displayText("Hello, World!")

sendGreetings("Roger", "Michael")
"""
tree = ast.parse(s)
f = FunCalls()
f.walk(tree)
print(dict(f.f_defs)) #the function definitions with signatures
calls = {a:b for a, b in f.f_calls if any(j == a for j, _ in f.f_defs)}    
print(calls)

输出:

{'displayText': ['text'], 'sendGreetings': ['sender', 'reciever']}
{'displayText': ['Hello, World!'], 'sendGreetings': ['Roger', 'Michael']}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接