to-string-tokens.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. var isValue = require("../../object/is-value")
  3. , esniff = require("esniff")
  4. , validFunction = require("../valid-function");
  5. var classRe = /^\s*class[\s{/}]/;
  6. module.exports = function () {
  7. var str = String(validFunction(this));
  8. if (classRe.test(str)) throw new Error("Class methods are not supported");
  9. var argsStartIndex
  10. , argsEndIndex
  11. , bodyStartIndex
  12. , bodyEndReverseIndex = -1
  13. , shouldTrimArgs = false;
  14. esniff(str, function (emitter, accessor) {
  15. emitter.once("trigger:(", function () { argsStartIndex = accessor.index + 1; });
  16. emitter.once("trigger:=", function () {
  17. if (isValue(argsStartIndex)) return;
  18. argsStartIndex = 0;
  19. argsEndIndex = accessor.index;
  20. shouldTrimArgs = true;
  21. if (!accessor.skipCodePart("=>")) {
  22. throw new Error("Unexpected function string: " + str);
  23. }
  24. accessor.skipWhitespace();
  25. if (!accessor.skipCodePart("{")) bodyEndReverseIndex = Infinity;
  26. bodyStartIndex = accessor.index;
  27. });
  28. emitter.on("trigger:)", function () {
  29. if (accessor.scopeDepth) return;
  30. argsEndIndex = accessor.index;
  31. accessor.skipCodePart(")");
  32. accessor.skipWhitespace();
  33. if (accessor.skipCodePart("=>")) {
  34. accessor.skipWhitespace();
  35. if (!accessor.skipCodePart("{")) bodyEndReverseIndex = Infinity;
  36. } else if (!accessor.skipCodePart("{")) {
  37. throw new Error("Unexpected function string: " + str);
  38. }
  39. bodyStartIndex = accessor.index;
  40. accessor.stop();
  41. });
  42. });
  43. var argsString = str.slice(argsStartIndex, argsEndIndex);
  44. if (shouldTrimArgs) argsString = argsString.trim();
  45. return { args: argsString, body: str.slice(bodyStartIndex, bodyEndReverseIndex) };
  46. };