5

Say I have a function:

function hi()
    print('hi')
end

I'd like to be able to take this function as an argument and perform analysis on it, such as listing all the function calls in it, seeing all the variables it references, etc.

Note that I'm not talking about analysing source code; I don't have the source text of the function, I just have the function object, i.e. this is being done at runtime.

The way I think you'd go about doing this is to get the AST of the function. But I don't know how to do that. So how would I go about getting the AST of a function (or otherwise analysing it if there's a better way)?

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249

3 Answers3

2

You may want to try my lbci, a bytecode inspector library.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Sorry, but I don't understand what the return values of the functions are for lbci. Is there any better documentation than the page that says "there isn't much documentation but it's simple and intuitive"? – Seth Carnegie Oct 01 '11 at 20:50
  • @Seth, I'm sorry there's no documentation. Try reading `test.lua`. If you still have questions, send me email. – lhf Oct 02 '11 at 19:43
1

I have to ask. Why don't you have the source? Was is obfuscated in some way?

Anyhow as mentioned, the AST - even though there really wasn't one to begin with in Lua, is not available via any runtime mechanism.

Though it is quite easy to obtain access to the source in many cases as it is being fed into the interpreter embedded or not (unless of course they only ship bytecode...

sylvanaar
  • 8,096
  • 37
  • 59
0

Abstract Syntax Trees are (pretty much by definition) a source-level concept.

So what you are perhaps looking for in a non-reflective compiled language would be a "decompiler"

Would this work?

http://luadec.luaforge.net/

  • What I really need is a Lua library that can take a function and produce the AST for it (or some other representation that I can use). If the only way to do that is to get the source of the function then pass the source to an analyser, then I guess that's just the way it is. But can you use luadec from lua, or is it just a program? That would require me to make it a lua extension (really want to avoid that) and distribute it with my application. – Seth Carnegie Sep 18 '11 at 21:48
  • Well if your source code is fixed you could always run an analysis at the time of compilation. Then embed the relevant data extracted from the analysis into your program. Or you could stylize your code in such a way that there is an explicit "announcement" registered by each function of what it calls, and you can further stylize it so that only those functions are allowed to be invoked at runtime... – HostileFork says dont trust SE Sep 18 '11 at 22:13
  • -OR- use a meta-circular language instead: http://en.wikipedia.org/wiki/Meta-circular_evaluator – HostileFork says dont trust SE Sep 18 '11 at 22:23