first_in_statement.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import {
  2. AST_Binary,
  3. AST_Conditional,
  4. AST_Chain,
  5. AST_Dot,
  6. AST_Object,
  7. AST_Sequence,
  8. AST_Statement,
  9. AST_Sub,
  10. AST_UnaryPostfix,
  11. AST_PrefixedTemplateString
  12. } from "../ast.js";
  13. // return true if the node at the top of the stack (that means the
  14. // innermost node in the current output) is lexically the first in
  15. // a statement.
  16. function first_in_statement(stack) {
  17. let node = stack.parent(-1);
  18. for (let i = 0, p; p = stack.parent(i); i++) {
  19. if (p instanceof AST_Statement && p.body === node)
  20. return true;
  21. if ((p instanceof AST_Sequence && p.expressions[0] === node) ||
  22. (p.TYPE === "Call" && p.expression === node) ||
  23. (p instanceof AST_PrefixedTemplateString && p.prefix === node) ||
  24. (p instanceof AST_Dot && p.expression === node) ||
  25. (p instanceof AST_Sub && p.expression === node) ||
  26. (p instanceof AST_Chain && p.expression === node) ||
  27. (p instanceof AST_Conditional && p.condition === node) ||
  28. (p instanceof AST_Binary && p.left === node) ||
  29. (p instanceof AST_UnaryPostfix && p.expression === node)
  30. ) {
  31. node = p;
  32. } else {
  33. return false;
  34. }
  35. }
  36. }
  37. // Returns whether the leftmost item in the expression is an object
  38. function left_is_object(node) {
  39. if (node instanceof AST_Object) return true;
  40. if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]);
  41. if (node.TYPE === "Call") return left_is_object(node.expression);
  42. if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix);
  43. if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression);
  44. if (node instanceof AST_Chain) return left_is_object(node.expression);
  45. if (node instanceof AST_Conditional) return left_is_object(node.condition);
  46. if (node instanceof AST_Binary) return left_is_object(node.left);
  47. if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression);
  48. return false;
  49. }
  50. export { first_in_statement, left_is_object };