evaluate.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. import { is_pure_native_value, is_pure_native_fn, is_pure_native_method } from "./native-objects.js";
  68. // methods to evaluate a constant expression
  69. function def_eval(node, func) {
  70. node.DEFMETHOD("_eval", func);
  71. }
  72. // Used to propagate a nullish short-circuit signal upwards through the chain.
  73. export const nullish = Symbol("This AST_Chain is nullish");
  74. // If the node has been successfully reduced to a constant,
  75. // then its value is returned; otherwise the element itself
  76. // is returned.
  77. // They can be distinguished as constant value is never a
  78. // descendant of AST_Node.
  79. AST_Node.DEFMETHOD("evaluate", function (compressor) {
  80. if (!compressor.option("evaluate"))
  81. return this;
  82. var val = this._eval(compressor, 1);
  83. if (!val || val instanceof RegExp)
  84. return val;
  85. if (typeof val == "function" || typeof val == "object" || val == nullish)
  86. return this;
  87. // Evaluated strings can be larger than the original expression
  88. if (typeof val === "string") {
  89. const unevaluated_size = this.size(compressor);
  90. if (val.length + 2 > unevaluated_size) return this;
  91. }
  92. return val;
  93. });
  94. var unaryPrefix = makePredicate("! ~ - + void");
  95. AST_Node.DEFMETHOD("is_constant", function () {
  96. // Accomodate when compress option evaluate=false
  97. // as well as the common constant expressions !0 and -1
  98. if (this instanceof AST_Constant) {
  99. return !(this instanceof AST_RegExp);
  100. } else {
  101. return this instanceof AST_UnaryPrefix
  102. && this.expression instanceof AST_Constant
  103. && unaryPrefix.has(this.operator);
  104. }
  105. });
  106. def_eval(AST_Statement, function () {
  107. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  108. });
  109. def_eval(AST_Lambda, return_this);
  110. def_eval(AST_Class, return_this);
  111. def_eval(AST_Node, return_this);
  112. def_eval(AST_Constant, function () {
  113. return this.getValue();
  114. });
  115. const supports_bigint = typeof BigInt === "function";
  116. def_eval(AST_BigInt, function () {
  117. if (supports_bigint) {
  118. return BigInt(this.value);
  119. } else {
  120. return this;
  121. }
  122. });
  123. def_eval(AST_RegExp, function (compressor) {
  124. let evaluated = compressor.evaluated_regexps.get(this.value);
  125. if (evaluated === undefined && regexp_is_safe(this.value.source)) {
  126. try {
  127. const { source, flags } = this.value;
  128. evaluated = new RegExp(source, flags);
  129. } catch (e) {
  130. evaluated = null;
  131. }
  132. compressor.evaluated_regexps.set(this.value, evaluated);
  133. }
  134. return evaluated || this;
  135. });
  136. def_eval(AST_TemplateString, function () {
  137. if (this.segments.length !== 1) return this;
  138. return this.segments[0].value;
  139. });
  140. def_eval(AST_Function, function (compressor) {
  141. if (compressor.option("unsafe")) {
  142. var fn = function () { };
  143. fn.node = this;
  144. fn.toString = () => this.print_to_string();
  145. return fn;
  146. }
  147. return this;
  148. });
  149. def_eval(AST_Array, function (compressor, depth) {
  150. if (compressor.option("unsafe")) {
  151. var elements = [];
  152. for (var i = 0, len = this.elements.length; i < len; i++) {
  153. var element = this.elements[i];
  154. var value = element._eval(compressor, depth);
  155. if (element === value)
  156. return this;
  157. elements.push(value);
  158. }
  159. return elements;
  160. }
  161. return this;
  162. });
  163. def_eval(AST_Object, function (compressor, depth) {
  164. if (compressor.option("unsafe")) {
  165. var val = {};
  166. for (var i = 0, len = this.properties.length; i < len; i++) {
  167. var prop = this.properties[i];
  168. if (prop instanceof AST_Expansion)
  169. return this;
  170. var key = prop.key;
  171. if (key instanceof AST_Symbol) {
  172. key = key.name;
  173. } else if (key instanceof AST_Node) {
  174. key = key._eval(compressor, depth);
  175. if (key === prop.key)
  176. return this;
  177. }
  178. if (typeof Object.prototype[key] === "function") {
  179. return this;
  180. }
  181. if (prop.value instanceof AST_Function)
  182. continue;
  183. val[key] = prop.value._eval(compressor, depth);
  184. if (val[key] === prop.value)
  185. return this;
  186. }
  187. return val;
  188. }
  189. return this;
  190. });
  191. var non_converting_unary = makePredicate("! typeof void");
  192. def_eval(AST_UnaryPrefix, function (compressor, depth) {
  193. var e = this.expression;
  194. // Function would be evaluated to an array and so typeof would
  195. // incorrectly return 'object'. Hence making is a special case.
  196. if (compressor.option("typeofs")
  197. && this.operator == "typeof"
  198. && (e instanceof AST_Lambda
  199. || e instanceof AST_SymbolRef
  200. && e.fixed_value() instanceof AST_Lambda)) {
  201. return typeof function () { };
  202. }
  203. if (!non_converting_unary.has(this.operator))
  204. depth++;
  205. e = e._eval(compressor, depth);
  206. if (e === this.expression)
  207. return this;
  208. switch (this.operator) {
  209. case "!": return !e;
  210. case "typeof":
  211. // typeof <RegExp> returns "object" or "function" on different platforms
  212. // so cannot evaluate reliably
  213. if (e instanceof RegExp)
  214. return this;
  215. return typeof e;
  216. case "void": return void e;
  217. case "~": return ~e;
  218. case "-": return -e;
  219. case "+": return +e;
  220. }
  221. return this;
  222. });
  223. var non_converting_binary = makePredicate("&& || ?? === !==");
  224. const identity_comparison = makePredicate("== != === !==");
  225. const has_identity = value => typeof value === "object"
  226. || typeof value === "function"
  227. || typeof value === "symbol";
  228. def_eval(AST_Binary, function (compressor, depth) {
  229. if (!non_converting_binary.has(this.operator))
  230. depth++;
  231. var left = this.left._eval(compressor, depth);
  232. if (left === this.left)
  233. return this;
  234. var right = this.right._eval(compressor, depth);
  235. if (right === this.right)
  236. return this;
  237. if (left != null
  238. && right != null
  239. && identity_comparison.has(this.operator)
  240. && has_identity(left)
  241. && has_identity(right)
  242. && typeof left === typeof right) {
  243. // Do not compare by reference
  244. return this;
  245. }
  246. // Do not mix BigInt and Number; Don't use `>>>` on BigInt or `/ 0n`
  247. if (
  248. (typeof left === "bigint") !== (typeof right === "bigint")
  249. || typeof left === "bigint"
  250. && (this.operator === ">>>"
  251. || this.operator === "/" && Number(right) === 0)
  252. ) {
  253. return this;
  254. }
  255. var result;
  256. switch (this.operator) {
  257. case "&&": result = left && right; break;
  258. case "||": result = left || right; break;
  259. case "??": result = left != null ? left : right; break;
  260. case "|": result = left | right; break;
  261. case "&": result = left & right; break;
  262. case "^": result = left ^ right; break;
  263. case "+": result = left + right; break;
  264. case "*": result = left * right; break;
  265. case "**": result = left ** right; break;
  266. case "/": result = left / right; break;
  267. case "%": result = left % right; break;
  268. case "-": result = left - right; break;
  269. case "<<": result = left << right; break;
  270. case ">>": result = left >> right; break;
  271. case ">>>": result = left >>> right; break;
  272. case "==": result = left == right; break;
  273. case "===": result = left === right; break;
  274. case "!=": result = 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. default:
  281. return this;
  282. }
  283. if (typeof result === "number" && isNaN(result) && compressor.find_parent(AST_With)) {
  284. // leave original expression as is
  285. return this;
  286. }
  287. return result;
  288. });
  289. def_eval(AST_Conditional, function (compressor, depth) {
  290. var condition = this.condition._eval(compressor, depth);
  291. if (condition === this.condition)
  292. return this;
  293. var node = condition ? this.consequent : this.alternative;
  294. var value = node._eval(compressor, depth);
  295. return value === node ? this : value;
  296. });
  297. // Set of AST_SymbolRef which are currently being evaluated.
  298. // Avoids infinite recursion of ._eval()
  299. const reentrant_ref_eval = new Set();
  300. def_eval(AST_SymbolRef, function (compressor, depth) {
  301. if (reentrant_ref_eval.has(this))
  302. return this;
  303. var fixed = this.fixed_value();
  304. if (!fixed)
  305. return this;
  306. reentrant_ref_eval.add(this);
  307. const value = fixed._eval(compressor, depth);
  308. reentrant_ref_eval.delete(this);
  309. if (value === fixed)
  310. return this;
  311. if (value && typeof value == "object") {
  312. var escaped = this.definition().escaped;
  313. if (escaped && depth > escaped)
  314. return this;
  315. }
  316. return value;
  317. });
  318. const global_objs = { Array, Math, Number, Object, String };
  319. const regexp_flags = new Set([
  320. "dotAll",
  321. "global",
  322. "ignoreCase",
  323. "multiline",
  324. "sticky",
  325. "unicode",
  326. ]);
  327. def_eval(AST_PropAccess, function (compressor, depth) {
  328. let obj = this.expression._eval(compressor, depth + 1);
  329. if (obj === nullish || (this.optional && obj == null)) return nullish;
  330. // `.length` of strings and arrays is always safe
  331. if (this.property === "length") {
  332. if (typeof obj === "string") {
  333. return obj.length;
  334. }
  335. const is_spreadless_array =
  336. obj instanceof AST_Array
  337. && obj.elements.every(el => !(el instanceof AST_Expansion));
  338. if (
  339. is_spreadless_array
  340. && obj.elements.every(el => !el.has_side_effects(compressor))
  341. ) {
  342. return obj.elements.length;
  343. }
  344. }
  345. if (compressor.option("unsafe")) {
  346. var key = this.property;
  347. if (key instanceof AST_Node) {
  348. key = key._eval(compressor, depth);
  349. if (key === this.property)
  350. return this;
  351. }
  352. var exp = this.expression;
  353. if (is_undeclared_ref(exp)) {
  354. var aa;
  355. var first_arg = exp.name === "hasOwnProperty"
  356. && key === "call"
  357. && (aa = compressor.parent() && compressor.parent().args)
  358. && (aa && aa[0]
  359. && aa[0].evaluate(compressor));
  360. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  361. if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) {
  362. return this.clone();
  363. }
  364. if (!is_pure_native_value(exp.name, key))
  365. return this;
  366. obj = global_objs[exp.name];
  367. } else {
  368. if (obj instanceof RegExp) {
  369. if (key == "source") {
  370. return regexp_source_fix(obj.source);
  371. } else if (key == "flags" || regexp_flags.has(key)) {
  372. return obj[key];
  373. }
  374. }
  375. if (!obj || obj === exp || !HOP(obj, key))
  376. return this;
  377. if (typeof obj == "function")
  378. switch (key) {
  379. case "name":
  380. return obj.node.name ? obj.node.name.name : "";
  381. case "length":
  382. return obj.node.length_property();
  383. default:
  384. return this;
  385. }
  386. }
  387. return obj[key];
  388. }
  389. return this;
  390. });
  391. def_eval(AST_Chain, function (compressor, depth) {
  392. const evaluated = this.expression._eval(compressor, depth);
  393. return evaluated === nullish
  394. ? undefined
  395. : evaluated === this.expression
  396. ? this
  397. : evaluated;
  398. });
  399. def_eval(AST_Call, function (compressor, depth) {
  400. var exp = this.expression;
  401. const callee = exp._eval(compressor, depth);
  402. if (callee === nullish || (this.optional && callee == null)) return nullish;
  403. if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
  404. var key = exp.property;
  405. if (key instanceof AST_Node) {
  406. key = key._eval(compressor, depth);
  407. if (key === exp.property)
  408. return this;
  409. }
  410. var val;
  411. var e = exp.expression;
  412. if (is_undeclared_ref(e)) {
  413. var first_arg = e.name === "hasOwnProperty" &&
  414. key === "call" &&
  415. (this.args[0] && this.args[0].evaluate(compressor));
  416. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  417. if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) {
  418. return this.clone();
  419. }
  420. if (!is_pure_native_fn(e.name, key)) return this;
  421. val = global_objs[e.name];
  422. } else {
  423. val = e._eval(compressor, depth + 1);
  424. if (val === e || !val)
  425. return this;
  426. if (!is_pure_native_method(val.constructor.name, key))
  427. return this;
  428. }
  429. var args = [];
  430. for (var i = 0, len = this.args.length; i < len; i++) {
  431. var arg = this.args[i];
  432. var value = arg._eval(compressor, depth);
  433. if (arg === value)
  434. return this;
  435. if (arg instanceof AST_Lambda)
  436. return this;
  437. args.push(value);
  438. }
  439. try {
  440. return val[key].apply(val, args);
  441. } catch (ex) {
  442. // We don't really care
  443. }
  444. }
  445. return this;
  446. });
  447. // Also a subclass of AST_Call
  448. def_eval(AST_New, return_this);