tc39 / proposal-do-expressions

Proposal for `do` expressions
MIT License
1.11k stars 14 forks source link

context free grammar #31

Closed majg0 closed 6 years ago

majg0 commented 6 years ago

The do is clashing with the do of do-while, making this not be a context free grammar. It should be in order to ease (and also speed up) parsing.

See the legendary http://www.informatik.uni-bremen.de/agbkb/lehre/ccfl/Material/ALSUdragonbook.pdf for more on this topic

pitaj commented 6 years ago

What keyword or syntax do you propose in its place?

do was used because it's a short keyword (2 letters), it's already used in a block-opening context, it's already a keyword so it can't be a breaking change, and it doesn't have a very specific meaning as a word (unlike if, else, while, etc)

majg0 commented 6 years ago

That makes sense.

I know this goes against the context-free grammar thing too, but why not ditch the keyword if it doesn't solve that problem anyway?

const foo = {
  const bar = 3
  bar * 2
}

console.log(bar) // undefined or error, depending on mode
console.log(foo) // 6
phiresky commented 6 years ago

Can you explain why this would change anything about the class of grammar? Syntactically, it seems like the do block can be parsed the same as a do/while block. Exactly the same as an if block with an optional else block. (There you also don't know if an else block is coming or not)

kenbellows commented 6 years ago

To add to @phiresky's point, it may be the same as a try ... catch ... finally where the catch and finally blocks are each optional (though one must be present). I guess the difference might be (and I'm no expert in this area, so feel free to tell me off if I'm wrong) that in the case of if .. else and try ... catch ... finally, whether or not the optional keywords and blocks are there, the whole thing is always a statement, whereas with do vs do ... while, the presence or absence of the while determines whether the do is a statement or an expression. How significant is that during parsing?

claudepache commented 6 years ago

The ES grammar does already allow { to start either a block or an object literal; function to start either a function declaration or a function expression; etc. A lookahead is used in order to force one interpretation in statement context, see:

https://tc39.github.io/ecma262/#sec-expression-statement

The same technique shall be used in order to disambiguate between do-while (valid only as statement) and do (valid only as expression). There is nothing new.

majg0 commented 6 years ago

Thank you all for making me wiser. I see the complexity better now. This issue can be closed, as the original intent is irrelevant now.