isAsyncOperation.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import {ContextualKeyword} from "../parser/tokenizer/keywords";
  2. /**
  3. * Determine whether this optional chain or nullish coalescing operation has any await statements in
  4. * it. If so, we'll need to transpile to an async operation.
  5. *
  6. * We compute this by walking the length of the operation and returning true if we see an await
  7. * keyword used as a real await (rather than an object key or property access). Nested optional
  8. * chain/nullish operations need to be tracked but don't silence await, but a nested async function
  9. * (or any other nested scope) will make the await not count.
  10. */
  11. export default function isAsyncOperation(tokens) {
  12. let index = tokens.currentIndex();
  13. let depth = 0;
  14. const startToken = tokens.currentToken();
  15. do {
  16. const token = tokens.tokens[index];
  17. if (token.isOptionalChainStart) {
  18. depth++;
  19. }
  20. if (token.isOptionalChainEnd) {
  21. depth--;
  22. }
  23. depth += token.numNullishCoalesceStarts;
  24. depth -= token.numNullishCoalesceEnds;
  25. if (
  26. token.contextualKeyword === ContextualKeyword._await &&
  27. token.identifierRole == null &&
  28. token.scopeDepth === startToken.scopeDepth
  29. ) {
  30. return true;
  31. }
  32. index += 1;
  33. } while (depth > 0 && index < tokens.tokens.length);
  34. return false;
  35. }