lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 7/14/06, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> Any special difficulties that I should be aware of?

Yes, bytecode for a register machine is harder than for a stack machine...
See Hisham's decompiler.
	http://www.inf.puc-rio.br/~hisham/luadec.pdf
	http://luadec.luaforge.net/

Actually, I did also write a Lua-to-C translator. I wrote it for
Lua-5.1-beta (didn't thoroughly test it on Lua 5.1.1, but I gave it a
quick run here and it seems to work).
I did not release before because it's of limited usefulness, being
more of a proof-of-concept than anything else. It's nice for studying
the Lua C API though.

I just put it up here, if anyone's interested:
http://www.inf.puc-rio.br/~hisham/luatoc.tar.gz

The main limitations are:
* upvalue handling - upvalues are not faithfully translated, but
converted to C-style upvalues, that have different semantics;
* coroutines - no way to handle them in a static translation like this
since they're presented as a library (even if we could, I'd need to
use Coco to replicate the semantics);
* tail-calls - they're downgraded to regular calls

Still, I've been able to use it to translate a slightly modified
version of itself (getting rid of tail-calls that were overflowing,
etc) and then translate it again, and it also translated successfully
all of the little tests from Lua's test/ directory (except for the
ones based in coroutines).

"luatoc" is written in Lua, and generates code that "gcc -ansi" is
happy with (only tested it in Linux with GCC but the generated code
should be portable, at least in theory ;) ). I'm using a driver
shell-script to call luac to generate a bytecode dump which is fed
into luatoc and then call gcc on the generated C file, but looking at
it, it should be easy to figure out how to run it in other
environments.

By the way, I spotted a buglet in the output of luac -l -l: print.c
needs to handle backslashes.

--- lua-5.1.1/src/print.old.c   2006-07-16 18:27:33.000000000 -0300
+++ lua-5.1.1/src/print.c       2006-07-16 18:27:51.000000000 -0300
@@ -34,2 +34,3 @@
   case '"': printf("\\\""); break;
+   case '\\': printf("\\\\"); break;
   case '\a': printf("\\a"); break;

Code containing strings using backslashes will need the above patch in
order to be translated properly.

-- Hisham