getFunctionExpression.js 1.9 KB

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