tools icon indicating copy to clipboard operation
tools copied to clipboard

🐛 Confusing error for await-expression inside non-async context

Open Boshen opened this issue 3 years ago • 4 comments

What happened?

In non-async context (Module),

function foo() {
  await bar;
}

await expression shows

error[SyntaxError]: Illegal use of `await` as an identifier inside of a module
  ┌─ main.js:2:3
  │
2 │   await bar;
  │   ^^^^^

error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none
  ┌─ main.js:2:9
  │
2 │   await bar;
  │   ------^^^
  │   │     │
  │   │     An explicit or implicit semicolon is expected here...
  │   ...Which is required to end this statement

which is super confusing, and the formatter will break it into two lines.

Expected result

acorn: Cannot use keyword 'await' outside an async function babel: Unexpected reserved word 'await'. swc: await isn't allowed in non-async function typescript: 'await' expressions are only allowed within async functions and at the top levels of modules.

Playground

https://play.rome.tools/?lineWidth=80&indentStyle=tab&quoteStyle=double&indentWidth=2&typescript=false&jsx=false&sourceType=module#ZgB1AG4AYwB0AGkAbwBuACAAZgBvAG8AKAApACAAewAKACAAIABhAHcAYQBpAHQAIABiAGEAcgA7AAoAfQA=

Code of Conduct

  • [X] I agree to follow Rome's Code of Conduct

Boshen avatar Apr 21 '22 16:04 Boshen

Hi @Boshen , could you please be more specific about what would you expect from our parser?

Even though our parser shows two errors, the first one seems to be cover the illegal use of await.

ematipico avatar Apr 22 '22 06:04 ematipico

I'm expecting a single error, and any mention of async context.

The two error messages are understandable from the spec perspective, but from user perspective it's rather confusing.

Also, the formatter breaks it into two statements just because we forgot to write async is also annoying in this case.

Boshen avatar Apr 22 '22 08:04 Boshen

Thank you! That makes sense now.

This should be an easy fix, I think: https://github.com/rome/tools/blob/main/crates/rome_js_parser/src/syntax/expr.rs#L1377-L1380

ematipico avatar Apr 22 '22 08:04 ematipico

I think the root cause of the issue is that await expression parsing is completely disabled in non-async context (here https://github.com/rome/tools/blob/main/crates/rome_js_parser/src/syntax/expr.rs#L1730) so await gets misinterpreted as an identifier expression, instead we should probably parse those expressions anyway but rewrite them as unknown expressions and emit a syntax error with a better explanation for the issue if they successfully parse but are not in an async context

leops avatar Apr 22 '22 11:04 leops

Fixed in #3573

MichaReiser avatar Nov 17 '22 09:11 MichaReiser