views:

447

answers:

3

I'm using a closed-source application that loads Lua scripts and allows some customization through modifying these scripts. Unfortunately that application is not very good at generating useful log output (all I get is 'script failed') if something goes wrong in one of the Lua scripts.

I realize that dynamic languages are pretty much resistant to static code analysis in the way C++ code can be analyzed for example.

I was hoping though, there would be a tool that runs through a Lua script and e.g. warns about variables that have not been defined in the context of a particular script.

Essentially what I'm looking for is a tool that for a script:

local a
print b

would output:

warning: script.lua(1): local 'a' is not used'
warning: script.lua(2): 'b' may not be defined'

It can only really be warnings for most things but that would still be useful! Does such a tool exist? Or maybe a Lua IDE with a feature like that build in?

Thanks, Chris

A: 

You need to find a parser for lua (should be available as open source) and use it to parse the script into a proper AST tree. Use that tree and a simple variable visibility tracker to find out when a variable is or isn't defined.

Usually the scoping rules are simple:

  • start with the top AST node and an empty scope
  • item look at the child statements for that node. Every variable declaration should be added in the current scope.
  • if a new scope is starting (for example via a { operator) create a new variable scope inheriting the variables in the current scope).
  • when a scope is ending (for example via } ) remove the current child variable scope and return to the parent.
  • Iterate carefully.

This will provide you with what variables are visible where inside the AST. You can use this information and if you also inspect the expressions AST nodes (read/write of variables) you can find out your information.

Toader Mihai Claudiu
You probably meant not "{" and "}" (which serve as table constructor in Lua), but "do" and "end" keywords (also various control constructs like if-then-else, two kind of for loops etc.).
Alexander Gladysh
I have no idea how the lua language looks like :-) But i assumed it has some idea of "variable scope".I actually did this kind of thing for Java recently.
Toader Mihai Claudiu
+4  A: 

Automated static code analysis for Lua is not an easy task in general. However, for a limited set of practical problems it is quite doable.

Quick googling for "lua lint" yields these two tools: lua-checker and Lua lint.

You may want to roll your own tool for your specific needs however.

Metalua is one of the most powerful tools for static Lua code analysis. For example, please see metalint, the tool for global variable usage analysis.

Please do not hesitate to post your question on Metalua mailing list. People there are usually very helpful.

Alexander Gladysh
+1  A: 

For checking globals, see this lua-l posting. Checking locals is harder.

lhf