moonscript icon indicating copy to clipboard operation
moonscript copied to clipboard

Compile single local function assignment into something like "local function funcname".

Open kazec opened this issue 8 years ago • 2 comments

Currently, moonc statement compiler compiles "fndef" node into two separate lines:

funcname = ->

into

local funcname
funcname = function() end

Which is not desirable, as a separate forward declaration introduces two additional instructions: LOADNIL and MOVE[1].

By digging into the moonscript commits back to 2011, I found out that the reason for this special treatment, which was introduced in b9e8b3014da407c9dd64a6c459b17cc6b8d90184 , is to allow recursive function calls.

However, by using Lua's syntactic sugar local function funcname, one can eliminate the additional instructions as well as allow recursive calls[2].

This is fairly easy to implement, I've made a quick tweak in https://github.com/kAzec/moonscript/commit/9612df6c8bce888737fe5aedcee661d1e265eb36 and updated compiler's sources and specs in https://github.com/kAzec/moonscript/commit/6c1c32dc2a1f44facd45c07881af02cd1646ecae and https://github.com/kAzec/moonscript/commit/a9cc66e49ce159d97c405526d472ce539d6b3f1f

After this tweak the above moonscript compiles to:

local function funcname() end

Note that this only affects a single, undeclared "name", so that the side effects should be minimal, though not fully examined.

I would be happy open up a PR if you agree about it. Also any feedback and suggestion will be greatly appreciated!

Thank you.

[1][2]: See this gist.

kazec avatar Oct 26 '17 12:10 kazec

Thanks for the patch, I think it's definitely worth the fix given how common this kind of output is. I see in your patch that you're doing a gsub on output from the value compiler, I would really prefer not to take that approach. Perhaps there's a way to use a statement compiler to catch those types of functions, instead of modifying the string of the value compiler

leafo avatar Oct 26 '17 16:10 leafo

Thanks for the response. I must admit this tweak is not so elegant.

As I'm not quite familiar with moonscript's codebase for now, I'll take a deeper look and try to figure out a new way to fix that.

Perhaps we should keep this issue open for now, until some actual progress can be made?

kazec avatar Oct 26 '17 18:10 kazec