function.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.FunctionParser = exports.dedentFunction = exports.functionToString = exports.USED_METHOD_KEY = void 0;
  4. const quote_1 = require("./quote");
  5. /**
  6. * Used in function stringification.
  7. */
  8. /* istanbul ignore next */
  9. const METHOD_NAMES_ARE_QUOTED = {
  10. " "() {
  11. /* Empty. */
  12. },
  13. }[" "]
  14. .toString()
  15. .charAt(0) === '"';
  16. const FUNCTION_PREFIXES = {
  17. Function: "function ",
  18. GeneratorFunction: "function* ",
  19. AsyncFunction: "async function ",
  20. AsyncGeneratorFunction: "async function* ",
  21. };
  22. const METHOD_PREFIXES = {
  23. Function: "",
  24. GeneratorFunction: "*",
  25. AsyncFunction: "async ",
  26. AsyncGeneratorFunction: "async *",
  27. };
  28. const TOKENS_PRECEDING_REGEXPS = new Set(("case delete else in instanceof new return throw typeof void " +
  29. ", ; : + - ! ~ & | ^ * / % < > ? =").split(" "));
  30. /**
  31. * Track function parser usage.
  32. */
  33. exports.USED_METHOD_KEY = new WeakSet();
  34. /**
  35. * Stringify a function.
  36. */
  37. const functionToString = (fn, space, next, key) => {
  38. const name = typeof key === "string" ? key : undefined;
  39. // Track in function parser for object stringify to avoid duplicate output.
  40. if (name !== undefined)
  41. exports.USED_METHOD_KEY.add(fn);
  42. return new FunctionParser(fn, space, next, name).stringify();
  43. };
  44. exports.functionToString = functionToString;
  45. /**
  46. * Rewrite a stringified function to remove initial indentation.
  47. */
  48. function dedentFunction(fnString) {
  49. let found;
  50. for (const line of fnString.split("\n").slice(1)) {
  51. const m = /^[\s\t]+/.exec(line);
  52. if (!m)
  53. return fnString; // Early exit without indent.
  54. const [str] = m;
  55. if (found === undefined)
  56. found = str;
  57. else if (str.length < found.length)
  58. found = str;
  59. }
  60. return found ? fnString.split(`\n${found}`).join("\n") : fnString;
  61. }
  62. exports.dedentFunction = dedentFunction;
  63. /**
  64. * Function parser and stringify.
  65. */
  66. class FunctionParser {
  67. constructor(fn, indent, next, key) {
  68. this.fn = fn;
  69. this.indent = indent;
  70. this.next = next;
  71. this.key = key;
  72. this.pos = 0;
  73. this.hadKeyword = false;
  74. this.fnString = Function.prototype.toString.call(fn);
  75. this.fnType = fn.constructor.name;
  76. this.keyQuote = key === undefined ? "" : quote_1.quoteKey(key, next);
  77. this.keyPrefix =
  78. key === undefined ? "" : `${this.keyQuote}:${indent ? " " : ""}`;
  79. this.isMethodCandidate =
  80. key === undefined ? false : this.fn.name === "" || this.fn.name === key;
  81. }
  82. stringify() {
  83. const value = this.tryParse();
  84. // If we can't stringify this function, return a void expression; for
  85. // bonus help with debugging, include the function as a string literal.
  86. if (!value) {
  87. return `${this.keyPrefix}void ${this.next(this.fnString)}`;
  88. }
  89. return dedentFunction(value);
  90. }
  91. getPrefix() {
  92. if (this.isMethodCandidate && !this.hadKeyword) {
  93. return METHOD_PREFIXES[this.fnType] + this.keyQuote;
  94. }
  95. return this.keyPrefix + FUNCTION_PREFIXES[this.fnType];
  96. }
  97. tryParse() {
  98. if (this.fnString[this.fnString.length - 1] !== "}") {
  99. // Must be an arrow function.
  100. return this.keyPrefix + this.fnString;
  101. }
  102. // Attempt to remove function prefix.
  103. if (this.fn.name) {
  104. const result = this.tryStrippingName();
  105. if (result)
  106. return result;
  107. }
  108. // Support class expressions.
  109. const prevPos = this.pos;
  110. if (this.consumeSyntax() === "class")
  111. return this.fnString;
  112. this.pos = prevPos;
  113. if (this.tryParsePrefixTokens()) {
  114. const result = this.tryStrippingName();
  115. if (result)
  116. return result;
  117. let offset = this.pos;
  118. switch (this.consumeSyntax("WORD_LIKE")) {
  119. case "WORD_LIKE":
  120. if (this.isMethodCandidate && !this.hadKeyword) {
  121. offset = this.pos;
  122. }
  123. case "()":
  124. if (this.fnString.substr(this.pos, 2) === "=>") {
  125. return this.keyPrefix + this.fnString;
  126. }
  127. this.pos = offset;
  128. case '"':
  129. case "'":
  130. case "[]":
  131. return this.getPrefix() + this.fnString.substr(this.pos);
  132. }
  133. }
  134. }
  135. /**
  136. * Attempt to parse the function from the current position by first stripping
  137. * the function's name from the front. This is not a fool-proof method on all
  138. * JavaScript engines, but yields good results on Node.js 4 (and slightly
  139. * less good results on Node.js 6 and 8).
  140. */
  141. tryStrippingName() {
  142. if (METHOD_NAMES_ARE_QUOTED) {
  143. // ... then this approach is unnecessary and yields false positives.
  144. return;
  145. }
  146. let start = this.pos;
  147. const prefix = this.fnString.substr(this.pos, this.fn.name.length);
  148. if (prefix === this.fn.name) {
  149. this.pos += prefix.length;
  150. if (this.consumeSyntax() === "()" &&
  151. this.consumeSyntax() === "{}" &&
  152. this.pos === this.fnString.length) {
  153. // Don't include the function's name if it will be included in the
  154. // prefix, or if it's invalid as a name in a function expression.
  155. if (this.isMethodCandidate || !quote_1.isValidVariableName(prefix)) {
  156. start += prefix.length;
  157. }
  158. return this.getPrefix() + this.fnString.substr(start);
  159. }
  160. }
  161. this.pos = start;
  162. }
  163. /**
  164. * Attempt to advance the parser past the keywords expected to be at the
  165. * start of this function's definition. This method sets `this.hadKeyword`
  166. * based on whether or not a `function` keyword is consumed.
  167. */
  168. tryParsePrefixTokens() {
  169. let posPrev = this.pos;
  170. this.hadKeyword = false;
  171. switch (this.fnType) {
  172. case "AsyncFunction":
  173. if (this.consumeSyntax() !== "async")
  174. return false;
  175. posPrev = this.pos;
  176. case "Function":
  177. if (this.consumeSyntax() === "function") {
  178. this.hadKeyword = true;
  179. }
  180. else {
  181. this.pos = posPrev;
  182. }
  183. return true;
  184. case "AsyncGeneratorFunction":
  185. if (this.consumeSyntax() !== "async")
  186. return false;
  187. case "GeneratorFunction":
  188. let token = this.consumeSyntax();
  189. if (token === "function") {
  190. token = this.consumeSyntax();
  191. this.hadKeyword = true;
  192. }
  193. return token === "*";
  194. }
  195. }
  196. /**
  197. * Advance the parser past one element of JavaScript syntax. This could be a
  198. * matched pair of delimiters, like braces or parentheses, or an atomic unit
  199. * like a keyword, variable, or operator. Return a normalized string
  200. * representation of the element parsed--for example, returns '{}' for a
  201. * matched pair of braces. Comments and whitespace are skipped.
  202. *
  203. * (This isn't a full parser, so the token scanning logic used here is as
  204. * simple as it can be. As a consequence, some things that are one token in
  205. * JavaScript, like decimal number literals or most multi-character operators
  206. * like '&&', are split into more than one token here. However, awareness of
  207. * some multi-character sequences like '=>' is necessary, so we match the few
  208. * of them that we care about.)
  209. */
  210. consumeSyntax(wordLikeToken) {
  211. const m = this.consumeMatch(/^(?:([A-Za-z_0-9$\xA0-\uFFFF]+)|=>|\+\+|\-\-|.)/);
  212. if (!m)
  213. return;
  214. const [token, match] = m;
  215. this.consumeWhitespace();
  216. if (match)
  217. return wordLikeToken || match;
  218. switch (token) {
  219. case "(":
  220. return this.consumeSyntaxUntil("(", ")");
  221. case "[":
  222. return this.consumeSyntaxUntil("[", "]");
  223. case "{":
  224. return this.consumeSyntaxUntil("{", "}");
  225. case "`":
  226. return this.consumeTemplate();
  227. case '"':
  228. return this.consumeRegExp(/^(?:[^\\"]|\\.)*"/, '"');
  229. case "'":
  230. return this.consumeRegExp(/^(?:[^\\']|\\.)*'/, "'");
  231. }
  232. return token;
  233. }
  234. consumeSyntaxUntil(startToken, endToken) {
  235. let isRegExpAllowed = true;
  236. for (;;) {
  237. const token = this.consumeSyntax();
  238. if (token === endToken)
  239. return startToken + endToken;
  240. if (!token || token === ")" || token === "]" || token === "}")
  241. return;
  242. if (token === "/" &&
  243. isRegExpAllowed &&
  244. this.consumeMatch(/^(?:\\.|[^\\\/\n[]|\[(?:\\.|[^\]])*\])+\/[a-z]*/)) {
  245. isRegExpAllowed = false;
  246. this.consumeWhitespace();
  247. }
  248. else {
  249. isRegExpAllowed = TOKENS_PRECEDING_REGEXPS.has(token);
  250. }
  251. }
  252. }
  253. consumeMatch(re) {
  254. const m = re.exec(this.fnString.substr(this.pos));
  255. if (m)
  256. this.pos += m[0].length;
  257. return m;
  258. }
  259. /**
  260. * Advance the parser past an arbitrary regular expression. Return `token`,
  261. * or the match object of the regexp.
  262. */
  263. consumeRegExp(re, token) {
  264. const m = re.exec(this.fnString.substr(this.pos));
  265. if (!m)
  266. return;
  267. this.pos += m[0].length;
  268. this.consumeWhitespace();
  269. return token;
  270. }
  271. /**
  272. * Advance the parser past a template string.
  273. */
  274. consumeTemplate() {
  275. for (;;) {
  276. this.consumeMatch(/^(?:[^`$\\]|\\.|\$(?!{))*/);
  277. if (this.fnString[this.pos] === "`") {
  278. this.pos++;
  279. this.consumeWhitespace();
  280. return "`";
  281. }
  282. if (this.fnString.substr(this.pos, 2) === "${") {
  283. this.pos += 2;
  284. this.consumeWhitespace();
  285. if (this.consumeSyntaxUntil("{", "}"))
  286. continue;
  287. }
  288. return;
  289. }
  290. }
  291. /**
  292. * Advance the parser past any whitespace or comments.
  293. */
  294. consumeWhitespace() {
  295. this.consumeMatch(/^(?:\s|\/\/.*|\/\*[^]*?\*\/)*/);
  296. }
  297. }
  298. exports.FunctionParser = FunctionParser;
  299. //# sourceMappingURL=function.js.map