Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error message on parsing await expression #1216

Closed
zen0wu opened this issue Apr 28, 2021 · 3 comments
Closed

Improve error message on parsing await expression #1216

zen0wu opened this issue Apr 28, 2021 · 3 comments

Comments

@zen0wu
Copy link

zen0wu commented Apr 28, 2021

With the following file, esbuild will print this seemingly confusing error message.

function f() { // This should really be an async function
  await f();
}
❯ npx esbuild test.ts
 > test.ts:2:8: error: Expected ";" but found "f"
    2 │   await f();
      ╵         ^

1 error

This is pretty hard to understand especially when this function definition is non-trivial. Not sure how much this factor into speed consideration since improving the error message here might involve changing how the parser works? But it would be nice to get it fixed.

Thanks!

@evanw
Copy link
Owner

evanw commented Apr 28, 2021

Sure. This seems simple enough. Here's the implementation from V8:

  void ExpectSemicolon() {
    // Check for automatic semicolon insertion according to
    // the rules given in ECMA-262, section 7.9, page 21.
    Token::Value tok = peek();
    if (V8_LIKELY(tok == Token::SEMICOLON)) {
      Next();
      return;
    }
    if (V8_LIKELY(scanner()->HasLineTerminatorBeforeNext() ||
                  Token::IsAutoSemicolon(tok))) {
      return;
    }

    if (scanner()->current_token() == Token::AWAIT && !is_async_function()) {
      ReportMessageAt(scanner()->location(),
                      flags().allow_harmony_top_level_await()
                          ? MessageTemplate::kAwaitNotInAsyncContext
                          : MessageTemplate::kAwaitNotInAsyncFunction);
      return;
    }

    ReportUnexpectedToken(Next());
  }

So basically: if you hit a syntax error and the previous token was an await, complain about the await instead.

@evanw evanw closed this as completed in d86a3b9 Apr 28, 2021
@evanw
Copy link
Owner

evanw commented Apr 28, 2021

The error message now looks like this:

❯ npx esbuild test.ts
 > example.js:2:2: error: "await" can only be used inside an "async" function
    2 │   await f();
      ╵   ~~~~~
   example.js:1:0: note: Consider adding the "async" keyword here
    1 │ function f() { // This should really be an async function
      │ ^
      ╵ async

1 error

@zen0wu
Copy link
Author

zen0wu commented Apr 28, 2021

Thanks for such speedy turnaround 🙌🏽 ! I have so much more faith in esbuild :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants