nodejs / node-eps

Node.js Enhancement Proposals for discussion on future API additions/changes to Node core
443 stars 66 forks source link

002- Clarification of import evaluation order (and how it affects REPLs) #40

Closed tolmasky closed 7 years ago

tolmasky commented 7 years ago

Apologies, if this is the wrong place to ask this, I will happily move it somewhere else. I'm one of the developers of Tonic (tonicdev.com) and have been wondering about the effect import would have on REPL behavior for a while now, specifically as it could potentially create a new divergence with evaluation order that doesn't currently exist with require.

If I understand correctly, the ES6 spec states that with code like this:

// code
import x from '../x'

"../x" will be parsed and evaluated BEFORE any code in the parent is run, essentially as if this had been done instead:

import x from '../x'
// code

The issue comes up with REPLs, where if you were to type "import" on the second prompt, it would necessarily have to import afterwards, leading to a divergence in behavior that REPLs didn't use to have with require if you were to take all the REPL inputs and concat them into a file:

5 + 5 < 10 import x from '../x' < whatever

--> 5 + 5 THEN '../x' vs. --> '../x' THEN 5 +5

This would have a devastating effect on Tonic, since it means that to maintain parity with single-file execution, any time someone types an import in a cell, we are forced to re-run the script from the first line (as opposed to the nice "pick up from where you left off" behavior it currently can deterministically/correctly exhibit).

For an analogy, this is equivalent to how in Tonic today, if you write a function that would, after hoisting, affect an earlier cell, we have to rewind the state of the machine and re-run from the earlier cell:

out

This however is rather explicit and semantic from the user. On the other hand, merely importing a new library on your 10th input of a REPL does not seem to obviously imply "please re-run everything from the first cell, as any file mutation that takes place in this input would technically have to precede all the actions in this code".

So I guess my questions are: 1) are my interpretations of these behaviors correct, and 2) if they are, is it possibly to propose a different evaluation order.

bmeck commented 7 years ago

1) yes 2) not at this point

Though you can create interesting things in REPLs by extracting stuff to an outer scope. First iteration on ESM support likely won't be supporting import statements in the REPL though.