evaluate.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. import {
  34. HOP,
  35. makePredicate,
  36. return_this,
  37. string_template,
  38. regexp_source_fix,
  39. regexp_is_safe,
  40. } from "../utils/index.js";
  41. import {
  42. AST_Array,
  43. AST_BigInt,
  44. AST_Binary,
  45. AST_Call,
  46. AST_Chain,
  47. AST_Class,
  48. AST_Conditional,
  49. AST_Constant,
  50. AST_Dot,
  51. AST_Expansion,
  52. AST_Function,
  53. AST_Lambda,
  54. AST_New,
  55. AST_Node,
  56. AST_Object,
  57. AST_PropAccess,
  58. AST_RegExp,
  59. AST_Statement,
  60. AST_Symbol,
  61. AST_SymbolRef,
  62. AST_TemplateString,
  63. AST_UnaryPrefix,
  64. AST_With,
  65. } from "../ast.js";
  66. import { is_undeclared_ref} from "./inference.js";
  67. // methods to evaluate a constant expression
  68. function def_eval(node, func) {
  69. node.DEFMETHOD("_eval", func);
  70. }
  71. // Used to propagate a nullish short-circuit signal upwards through the chain.
  72. export const nullish = Symbol("This AST_Chain is nullish");
  73. // If the node has been successfully reduced to a constant,
  74. // then its value is returned; otherwise the element itself
  75. // is returned.
  76. // They can be distinguished as constant value is never a
  77. // descendant of AST_Node.
  78. AST_Node.DEFMETHOD("evaluate", function (compressor) {
  79. if (!compressor.option("evaluate"))
  80. return this;
  81. var val = this._eval(compressor, 1);
  82. if (!val || val instanceof RegExp)
  83. return val;
  84. if (typeof val == "function" || typeof val == "object" || val == nullish)
  85. return this;
  86. // Evaluated strings can be larger than the original expression
  87. if (typeof val === "string") {
  88. const unevaluated_size = this.size(compressor);
  89. if (val.length + 2 > unevaluated_size) return this;
  90. }
  91. return val;
  92. });
  93. var unaryPrefix = makePredicate("! ~ - + void");
  94. AST_Node.DEFMETHOD("is_constant", function () {
  95. // Accomodate when compress option evaluate=false
  96. // as well as the common constant expressions !0 and -1
  97. if (this instanceof AST_Constant) {
  98. return !(this instanceof AST_RegExp);
  99. } else {
  100. return this instanceof AST_UnaryPrefix
  101. && unaryPrefix.has(this.operator)
  102. && (
  103. // `this.expression` may be an `AST_RegExp`,
  104. // so not only `.is_constant()`.
  105. this.expression instanceof AST_Constant
  106. || this.expression.is_constant()
  107. );
  108. }
  109. });
  110. def_eval(AST_Statement, function () {
  111. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  112. });
  113. def_eval(AST_Lambda, return_this);
  114. def_eval(AST_Class, return_this);
  115. def_eval(AST_Node, return_this);
  116. def_eval(AST_Constant, function () {
  117. return this.getValue();
  118. });
  119. const supports_bigint = typeof BigInt === "function";
  120. def_eval(AST_BigInt, function () {
  121. if (supports_bigint) {
  122. return BigInt(this.value);
  123. } else {
  124. return this;
  125. }
  126. });
  127. def_eval(AST_RegExp, function (compressor) {
  128. let evaluated = compressor.evaluated_regexps.get(this.value);
  129. if (evaluated === undefined && regexp_is_safe(this.value.source)) {
  130. try {
  131. const { source, flags } = this.value;
  132. evaluated = new RegExp(source, flags);
  133. } catch (e) {
  134. evaluated = null;
  135. }
  136. compressor.evaluated_regexps.set(this.value, evaluated);
  137. }
  138. return evaluated || this;
  139. });
  140. def_eval(AST_TemplateString, function () {
  141. if (this.segments.length !== 1) return this;
  142. return this.segments[0].value;
  143. });
  144. def_eval(AST_Function, function (compressor) {
  145. if (compressor.option("unsafe")) {
  146. var fn = function () { };
  147. fn.node = this;
  148. fn.toString = () => this.print_to_string();
  149. return fn;
  150. }
  151. return this;
  152. });
  153. def_eval(AST_Array, function (compressor, depth) {
  154. if (compressor.option("unsafe")) {
  155. var elements = [];
  156. for (var i = 0, len = this.elements.length; i < len; i++) {
  157. var element = this.elements[i];
  158. var value = element._eval(compressor, depth);
  159. if (element === value)
  160. return this;
  161. elements.push(value);
  162. }
  163. return elements;
  164. }
  165. return this;
  166. });
  167. def_eval(AST_Object, function (compressor, depth) {
  168. if (compressor.option("unsafe")) {
  169. var val = {};
  170. for (var i = 0, len = this.properties.length; i < len; i++) {
  171. var prop = this.properties[i];
  172. if (prop instanceof AST_Expansion)
  173. return this;
  174. var key = prop.key;
  175. if (key instanceof AST_Symbol) {
  176. key = key.name;
  177. } else if (key instanceof AST_Node) {
  178. key = key._eval(compressor, depth);
  179. if (key === prop.key)
  180. return this;
  181. }
  182. if (typeof Object.prototype[key] === "function") {
  183. return this;
  184. }
  185. if (prop.value instanceof AST_Function)
  186. continue;
  187. val[key] = prop.value._eval(compressor, depth);
  188. if (val[key] === prop.value)
  189. return this;
  190. }
  191. return val;
  192. }
  193. return this;
  194. });
  195. var non_converting_unary = makePredicate("! typeof void");
  196. def_eval(AST_UnaryPrefix, function (compressor, depth) {
  197. var e = this.expression;
  198. if (compressor.option("typeofs")
  199. && this.operator == "typeof") {
  200. // Function would be evaluated to an array and so typeof would
  201. // incorrectly return 'object'. Hence making is a special case.
  202. if (e instanceof AST_Lambda
  203. || e instanceof AST_SymbolRef
  204. && e.fixed_value() instanceof AST_Lambda) {
  205. return typeof function () { };
  206. }
  207. if (
  208. (e instanceof AST_Object
  209. || e instanceof AST_Array
  210. || (e instanceof AST_SymbolRef
  211. && (e.fixed_value() instanceof AST_Object
  212. || e.fixed_value() instanceof AST_Array)))
  213. && !e.has_side_effects(compressor)
  214. ) {
  215. return typeof {};
  216. }
  217. }
  218. if (!non_converting_unary.has(this.operator))
  219. depth++;
  220. e = e._eval(compressor, depth);
  221. if (e === this.expression)
  222. return this;
  223. switch (this.operator) {
  224. case "!": return !e;
  225. case "typeof":
  226. // typeof <RegExp> returns "object" or "function" on different platforms
  227. // so cannot evaluate reliably
  228. if (e instanceof RegExp)
  229. return this;
  230. return typeof e;
  231. case "void": return void e;
  232. case "~": return ~e;
  233. case "-": return -e;
  234. case "+": return +e;
  235. }
  236. return this;
  237. });
  238. var non_converting_binary = makePredicate("&& || ?? === !==");
  239. const identity_comparison = makePredicate("== != === !==");
  240. const has_identity = value => typeof value === "object"
  241. || typeof value === "function"
  242. || typeof value === "symbol";
  243. def_eval(AST_Binary, function (compressor, depth) {
  244. if (!non_converting_binary.has(this.operator))
  245. depth++;
  246. var left = this.left._eval(compressor, depth);
  247. if (left === this.left)
  248. return this;
  249. var right = this.right._eval(compressor, depth);
  250. if (right === this.right)
  251. return this;
  252. if (left != null
  253. && right != null
  254. && identity_comparison.has(this.operator)
  255. && has_identity(left)
  256. && has_identity(right)
  257. && typeof left === typeof right) {
  258. // Do not compare by reference
  259. return this;
  260. }
  261. // Do not mix BigInt and Number; Don't use `>>>` on BigInt or `/ 0n`
  262. if (
  263. (typeof left === "bigint") !== (typeof right === "bigint")
  264. || typeof left === "bigint"
  265. && (this.operator === ">>>"
  266. || this.operator === "/" && Number(right) === 0)
  267. ) {
  268. return this;
  269. }
  270. var result;
  271. switch (this.operator) {
  272. case "&&": result = left && right; break;
  273. case "||": result = left || right; break;
  274. case "??": result = left != null ? left : right; break;
  275. case "|": result = left | right; break;
  276. case "&": result = left & right; break;
  277. case "^": result = left ^ right; break;
  278. case "+": result = left + right; break;
  279. case "*": result = left * right; break;
  280. case "**": result = left ** right; break;
  281. case "/": result = left / right; break;
  282. case "%": result = left % right; break;
  283. case "-": result = left - right; break;
  284. case "<<": result = left << right; break;
  285. case ">>": result = left >> right; break;
  286. case ">>>": result = left >>> right; break;
  287. case "==": result = left == right; break;
  288. case "===": result = left === right; break;
  289. case "!=": result = left != right; break;
  290. case "!==": result = left !== right; break;
  291. case "<": result = left < right; break;
  292. case "<=": result = left <= right; break;
  293. case ">": result = left > right; break;
  294. case ">=": result = left >= right; break;
  295. default:
  296. return this;
  297. }
  298. if (typeof result === "number" && isNaN(result) && compressor.find_parent(AST_With)) {
  299. // leave original expression as is
  300. return this;
  301. }
  302. return result;
  303. });
  304. def_eval(AST_Conditional, function (compressor, depth) {
  305. var condition = this.condition._eval(compressor, depth);
  306. if (condition === this.condition)
  307. return this;
  308. var node = condition ? this.consequent : this.alternative;
  309. var value = node._eval(compressor, depth);
  310. return value === node ? this : value;
  311. });
  312. // Set of AST_SymbolRef which are currently being evaluated.
  313. // Avoids infinite recursion of ._eval()
  314. const reentrant_ref_eval = new Set();
  315. def_eval(AST_SymbolRef, function (compressor, depth) {
  316. if (reentrant_ref_eval.has(this))
  317. return this;
  318. var fixed = this.fixed_value();
  319. if (!fixed)
  320. return this;
  321. reentrant_ref_eval.add(this);
  322. const value = fixed._eval(compressor, depth);
  323. reentrant_ref_eval.delete(this);
  324. if (value === fixed)
  325. return this;
  326. if (value && typeof value == "object") {
  327. var escaped = this.definition().escaped;
  328. if (escaped && depth > escaped)
  329. return this;
  330. }
  331. return value;
  332. });
  333. def_eval(AST_Chain, function (compressor, depth) {
  334. const evaluated = this.expression._eval(compressor, depth, /*ast_chain=*/true);
  335. return evaluated === nullish
  336. ? undefined
  337. : evaluated === this.expression
  338. ? this
  339. : evaluated;
  340. });
  341. const global_objs = { Array, Math, Number, Object, String };
  342. const regexp_flags = new Set([
  343. "dotAll",
  344. "global",
  345. "ignoreCase",
  346. "multiline",
  347. "sticky",
  348. "unicode",
  349. ]);
  350. def_eval(AST_PropAccess, function (compressor, depth, ast_chain) {
  351. let obj = (ast_chain || this.property === "length" || compressor.option("unsafe"))
  352. && this.expression._eval(compressor, depth + 1, ast_chain);
  353. if (ast_chain) {
  354. if (obj === nullish || (this.optional && obj == null)) return nullish;
  355. }
  356. // `.length` of strings and arrays is always safe
  357. if (this.property === "length") {
  358. if (typeof obj === "string") {
  359. return obj.length;
  360. }
  361. const is_spreadless_array =
  362. obj instanceof AST_Array
  363. && obj.elements.every(el => !(el instanceof AST_Expansion));
  364. if (
  365. is_spreadless_array
  366. && obj.elements.every(el => !el.has_side_effects(compressor))
  367. ) {
  368. return obj.elements.length;
  369. }
  370. }
  371. if (compressor.option("unsafe")) {
  372. var key = this.property;
  373. if (key instanceof AST_Node) {
  374. key = key._eval(compressor, depth);
  375. if (key === this.property)
  376. return this;
  377. }
  378. var exp = this.expression;
  379. if (is_undeclared_ref(exp)) {
  380. var aa;
  381. var first_arg = exp.name === "hasOwnProperty"
  382. && key === "call"
  383. && (aa = compressor.parent() && compressor.parent().args)
  384. && (aa && aa[0]
  385. && aa[0].evaluate(compressor));
  386. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  387. if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) {
  388. return this.clone();
  389. }
  390. if (!compressor.is_pure_native_static_property(exp.name, key))
  391. return this;
  392. obj = global_objs[exp.name];
  393. } else {
  394. if (obj instanceof RegExp) {
  395. if (key == "source") {
  396. return regexp_source_fix(obj.source);
  397. } else if (key == "flags" || regexp_flags.has(key)) {
  398. return obj[key];
  399. }
  400. }
  401. if (!obj || obj === exp || !HOP(obj, key))
  402. return this;
  403. if (typeof obj == "function")
  404. switch (key) {
  405. case "name":
  406. return obj.node.name ? obj.node.name.name : "";
  407. case "length":
  408. return obj.node.length_property();
  409. default:
  410. return this;
  411. }
  412. }
  413. return obj[key];
  414. }
  415. return this;
  416. });
  417. def_eval(AST_Call, function (compressor, depth, ast_chain) {
  418. var exp = this.expression;
  419. if (ast_chain) {
  420. const callee = exp._eval(compressor, depth, ast_chain);
  421. if (callee === nullish || (this.optional && callee == null)) return nullish;
  422. }
  423. if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
  424. var key = exp.property;
  425. if (key instanceof AST_Node) {
  426. key = key._eval(compressor, depth);
  427. if (typeof key !== "string" && typeof key !== "number")
  428. return this;
  429. }
  430. var val;
  431. var e = exp.expression;
  432. if (is_undeclared_ref(e)) {
  433. var first_arg = e.name === "hasOwnProperty" &&
  434. key === "call" &&
  435. (this.args[0] && this.args[0].evaluate(compressor));
  436. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  437. if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) {
  438. return this.clone();
  439. }
  440. if (!compressor.is_pure_native_static_fn(e.name, key)) return this;
  441. val = global_objs[e.name];
  442. } else {
  443. val = e._eval(compressor, depth + 1, /* don't pass ast_chain (exponential work) */);
  444. if (val === e || !val)
  445. return this;
  446. if (!compressor.is_pure_native_method(val.constructor.name, key))
  447. return this;
  448. }
  449. var args = [];
  450. for (var i = 0, len = this.args.length; i < len; i++) {
  451. var arg = this.args[i];
  452. var value = arg._eval(compressor, depth);
  453. if (arg === value)
  454. return this;
  455. if (arg instanceof AST_Lambda)
  456. return this;
  457. args.push(value);
  458. }
  459. try {
  460. return val[key].apply(val, args);
  461. } catch (ex) {
  462. // We don't really care
  463. }
  464. }
  465. return this;
  466. });
  467. // Also a subclass of AST_Call
  468. def_eval(AST_New, return_this);