getFunctionExpression.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */
  7. /** @typedef {import("estree").Expression} Expression */
  8. /** @typedef {import("estree").FunctionExpression} FunctionExpression */
  9. /** @typedef {import("estree").SpreadElement} SpreadElement */
  10. /**
  11. * @param {Expression | SpreadElement} expr expressions
  12. * @returns {{fn: FunctionExpression | ArrowFunctionExpression, expressions: (Expression | SpreadElement)[], needThis: boolean | undefined } | undefined} function expression with additional information
  13. */
  14. module.exports = expr => {
  15. // <FunctionExpression>
  16. if (
  17. expr.type === "FunctionExpression" ||
  18. expr.type === "ArrowFunctionExpression"
  19. ) {
  20. return {
  21. fn: expr,
  22. expressions: [],
  23. needThis: false
  24. };
  25. }
  26. // <FunctionExpression>.bind(<Expression>)
  27. if (
  28. expr.type === "CallExpression" &&
  29. expr.callee.type === "MemberExpression" &&
  30. expr.callee.object.type === "FunctionExpression" &&
  31. expr.callee.property.type === "Identifier" &&
  32. expr.callee.property.name === "bind" &&
  33. expr.arguments.length === 1
  34. ) {
  35. return {
  36. fn: expr.callee.object,
  37. expressions: [expr.arguments[0]],
  38. needThis: undefined
  39. };
  40. }
  41. // (function(_this) {return <FunctionExpression>})(this) (Coffeescript)
  42. if (
  43. expr.type === "CallExpression" &&
  44. expr.callee.type === "FunctionExpression" &&
  45. expr.callee.body.type === "BlockStatement" &&
  46. expr.arguments.length === 1 &&
  47. expr.arguments[0].type === "ThisExpression" &&
  48. expr.callee.body.body &&
  49. expr.callee.body.body.length === 1 &&
  50. expr.callee.body.body[0].type === "ReturnStatement" &&
  51. expr.callee.body.body[0].argument &&
  52. expr.callee.body.body[0].argument.type === "FunctionExpression"
  53. ) {
  54. return {
  55. fn: expr.callee.body.body[0].argument,
  56. expressions: [],
  57. needThis: true
  58. };
  59. }
  60. };