Rich-Harris / code-red

Experimental toolkit for writing x-to-JavaScript compilers
MIT License
333 stars 22 forks source link

Function declarations/expressions with `#` names not properly handled #10

Closed Conduitry closed 4 years ago

Conduitry commented 4 years ago
cr.print(cr.b`function #foo() { }`).code // => 'function #foo() {\n\t\n}'

If this were handled correctly, it would allow a nice solution to https://github.com/sveltejs/svelte/issues/3900

Conduitry commented 4 years ago

The only situation in which this really needs deconflicting is when there's code inside the function trying to access a variable foo declared outside the function. I don't know how this library handles this though, so it might just be easier to deconflict function #foo() { } as though it were a regular variable declaration.

Conduitry commented 4 years ago

Actually, no, we can only cut corners when it's a named function expression, not a function declaration. It seems easiest to just always deconflict this.

diff --git a/src/print/handlers.ts b/src/print/handlers.ts
index 240fc8e..fd2240a 100644
--- a/src/print/handlers.ts
+++ b/src/print/handlers.ts
@@ -569,7 +569,7 @@ const handlers: Record<string, Handler> = {

        if (node.async) chunks.push(c('async '));
        chunks.push(c(node.generator ? 'function* ' : 'function '));
-       if (node.id) chunks.push(c(node.id.name, node.id));
+       if (node.id) chunks.push(...handle(node.id, state));
        chunks.push(c('('));

        const params = node.params.map(p => handle(p, {

This looks like it works. PR coming soon.