munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.75k stars 1.03k forks source link

Function definition as expression rather than statement? #1014

Closed gvwilson closed 2 years ago

gvwilson commented 2 years ago

I'd like to see if I can turn function definition into an expression, e.g.:

var add = fun(left, right){ return left + right; };

(I'm a fan of Array.map and the like...) I think I understand how to do this as written; what I'm struggling with is that last semi-colon. Is there a simple way to modify the parser to make it unnecessary in situations like this?

RevengerWizard commented 2 years ago

Actually, making function definitions as expression is really easy, for those who will read this really late answer just add a new prefix function:

static void anonymous(bool can_assign)
{
    function(TYPE_FUNCTION);
}

and then in the rules array add it as a prefix to the TOKEN_FUNCTION

...
[TOKEN_FUNCTION] = { anonymous, NULL, PREC_NONE }
...

Doing so, you can already start thinking about all the crazy stuff it could come along, like, lists of functions, maps of lists of functions, ecc.

About the semicolon at the end of the expression, in my implementation I just scrapped it entirely and made it optional, since outside of the return case it's just consumed and not really used.