oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
72.82k stars 2.64k forks source link

`Function.toString()` returning strange strings #3248

Open simylein opened 1 year ago

simylein commented 1 year ago

What version of Bun is running?

0.6.7

What platform is your computer?

Darwin 22.5.0 arm64 arm

What steps can reproduce the bug?

run the following code with bun and node

const findUser = () => void 0;
const checkTodoAccess = () => void 0;
const findTodo = () => void 0;

const handler = (userId, todoId) => {
    const user = findUser(userId);
    checkTodoAccess(user);
    return findTodo(todoId);
};

console.log(handler.toString());

What is the expected behavior?

(userId, todoId) => {
        const user = findUser(userId);
        checkTodoAccess(user);
        return findTodo(todoId);
}

What do you see instead?

(userId, todoId) => {
  const user = findUser(userId);
  return checkTodoAccess(user), findTodo(todoId);
}

Additional information

I figured if the return value of a function is not used it gets appended with a comma somehow?

mikrosystheme commented 1 year ago

This is very bad and in violation of the ES specs. Function.prototype.toString() is required to return the exact source text used to define the function, whitespaces included. Is it at least possible to disable the minifier and/or any source transformation performed by Bun (given a javascript source file)?

Jarred-Sumner commented 1 year ago

Bun runs the JavaScript minifier on every file by default, which means the input source is not exactly the output source. It's reasonable to suggest we modify .toString to be the sourcemap'd source code, though it would incur an additional performance hit and won't always be possible

On the other hand, if you must rely on the output of Function.toString() to be correct, you can stick // @bun at the top of the file and Bun will skip running the transpiler on it. Note that this can cause various things to break, Bun relies on the transpiler at runtime for certain features like bun:test, the bun import (it is rewritten to globalThis.Bun), JSX, TypeScript support, and a handful of other things.

nektro commented 3 months ago

are you still able to reproduce this? it appears to be working for me in Bun 1.1.9 (you may need to run bun upgrade)

❯ bun-debug index.js 
(userId, todoId) => {
  const user = findUser(userId);
  checkTodoAccess(user);
  return findTodo(todoId);
}
Jarred-Sumner commented 3 months ago

@nektro this should continue to occur. We don't do quite as much minification as we did before, but we still do remove comments, some conditional expressions, and we transform function statements into function expressions.