evaluate.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. } from "../utils/index.js";
  40. import {
  41. AST_Array,
  42. AST_BigInt,
  43. AST_Binary,
  44. AST_Call,
  45. AST_Chain,
  46. AST_Class,
  47. AST_Conditional,
  48. AST_Constant,
  49. AST_Dot,
  50. AST_Expansion,
  51. AST_Function,
  52. AST_Lambda,
  53. AST_New,
  54. AST_Node,
  55. AST_Object,
  56. AST_PropAccess,
  57. AST_RegExp,
  58. AST_Statement,
  59. AST_Symbol,
  60. AST_SymbolRef,
  61. AST_TemplateString,
  62. AST_UnaryPrefix,
  63. AST_With,
  64. } from "../ast.js";
  65. import { is_undeclared_ref} from "./inference.js";
  66. import { is_pure_native_value, is_pure_native_fn, is_pure_native_method } from "./native-objects.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. return val;
  87. });
  88. var unaryPrefix = makePredicate("! ~ - + void");
  89. AST_Node.DEFMETHOD("is_constant", function () {
  90. // Accomodate when compress option evaluate=false
  91. // as well as the common constant expressions !0 and -1
  92. if (this instanceof AST_Constant) {
  93. return !(this instanceof AST_RegExp);
  94. } else {
  95. return this instanceof AST_UnaryPrefix
  96. && this.expression instanceof AST_Constant
  97. && unaryPrefix.has(this.operator);
  98. }
  99. });
  100. def_eval(AST_Statement, function () {
  101. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  102. });
  103. def_eval(AST_Lambda, return_this);
  104. def_eval(AST_Class, return_this);
  105. def_eval(AST_Node, return_this);
  106. def_eval(AST_Constant, function () {
  107. return this.getValue();
  108. });
  109. def_eval(AST_BigInt, return_this);
  110. def_eval(AST_RegExp, function (compressor) {
  111. let evaluated = compressor.evaluated_regexps.get(this);
  112. if (evaluated === undefined) {
  113. try {
  114. evaluated = (0, eval)(this.print_to_string());
  115. } catch (e) {
  116. evaluated = null;
  117. }
  118. compressor.evaluated_regexps.set(this, evaluated);
  119. }
  120. return evaluated || this;
  121. });
  122. def_eval(AST_TemplateString, function () {
  123. if (this.segments.length !== 1) return this;
  124. return this.segments[0].value;
  125. });
  126. def_eval(AST_Function, function (compressor) {
  127. if (compressor.option("unsafe")) {
  128. var fn = function () { };
  129. fn.node = this;
  130. fn.toString = () => this.print_to_string();
  131. return fn;
  132. }
  133. return this;
  134. });
  135. def_eval(AST_Array, function (compressor, depth) {
  136. if (compressor.option("unsafe")) {
  137. var elements = [];
  138. for (var i = 0, len = this.elements.length; i < len; i++) {
  139. var element = this.elements[i];
  140. var value = element._eval(compressor, depth);
  141. if (element === value)
  142. return this;
  143. elements.push(value);
  144. }
  145. return elements;
  146. }
  147. return this;
  148. });
  149. def_eval(AST_Object, function (compressor, depth) {
  150. if (compressor.option("unsafe")) {
  151. var val = {};
  152. for (var i = 0, len = this.properties.length; i < len; i++) {
  153. var prop = this.properties[i];
  154. if (prop instanceof AST_Expansion)
  155. return this;
  156. var key = prop.key;
  157. if (key instanceof AST_Symbol) {
  158. key = key.name;
  159. } else if (key instanceof AST_Node) {
  160. key = key._eval(compressor, depth);
  161. if (key === prop.key)
  162. return this;
  163. }
  164. if (typeof Object.prototype[key] === "function") {
  165. return this;
  166. }
  167. if (prop.value instanceof AST_Function)
  168. continue;
  169. val[key] = prop.value._eval(compressor, depth);
  170. if (val[key] === prop.value)
  171. return this;
  172. }
  173. return val;
  174. }
  175. return this;
  176. });
  177. var non_converting_unary = makePredicate("! typeof void");
  178. def_eval(AST_UnaryPrefix, function (compressor, depth) {
  179. var e = this.expression;
  180. // Function would be evaluated to an array and so typeof would
  181. // incorrectly return 'object'. Hence making is a special case.
  182. if (compressor.option("typeofs")
  183. && this.operator == "typeof"
  184. && (e instanceof AST_Lambda
  185. || e instanceof AST_SymbolRef
  186. && e.fixed_value() instanceof AST_Lambda)) {
  187. return typeof function () { };
  188. }
  189. if (!non_converting_unary.has(this.operator))
  190. depth++;
  191. e = e._eval(compressor, depth);
  192. if (e === this.expression)
  193. return this;
  194. switch (this.operator) {
  195. case "!": return !e;
  196. case "typeof":
  197. // typeof <RegExp> returns "object" or "function" on different platforms
  198. // so cannot evaluate reliably
  199. if (e instanceof RegExp)
  200. return this;
  201. return typeof e;
  202. case "void": return void e;
  203. case "~": return ~e;
  204. case "-": return -e;
  205. case "+": return +e;
  206. }
  207. return this;
  208. });
  209. var non_converting_binary = makePredicate("&& || ?? === !==");
  210. const identity_comparison = makePredicate("== != === !==");
  211. const has_identity = value => typeof value === "object"
  212. || typeof value === "function"
  213. || typeof value === "symbol";
  214. def_eval(AST_Binary, function (compressor, depth) {
  215. if (!non_converting_binary.has(this.operator))
  216. depth++;
  217. var left = this.left._eval(compressor, depth);
  218. if (left === this.left)
  219. return this;
  220. var right = this.right._eval(compressor, depth);
  221. if (right === this.right)
  222. return this;
  223. var result;
  224. if (left != null
  225. && right != null
  226. && identity_comparison.has(this.operator)
  227. && has_identity(left)
  228. && has_identity(right)
  229. && typeof left === typeof right) {
  230. // Do not compare by reference
  231. return this;
  232. }
  233. switch (this.operator) {
  234. case "&&": result = left && right; break;
  235. case "||": result = left || right; break;
  236. case "??": result = left != null ? left : right; break;
  237. case "|": result = left | right; break;
  238. case "&": result = left & right; break;
  239. case "^": result = left ^ right; break;
  240. case "+": result = left + right; break;
  241. case "*": result = left * right; break;
  242. case "**": result = Math.pow(left, right); break;
  243. case "/": result = left / right; break;
  244. case "%": result = left % right; break;
  245. case "-": result = left - right; break;
  246. case "<<": result = left << right; break;
  247. case ">>": result = left >> right; break;
  248. case ">>>": result = left >>> right; break;
  249. case "==": result = left == right; break;
  250. case "===": result = left === right; break;
  251. case "!=": result = left != right; break;
  252. case "!==": result = left !== right; break;
  253. case "<": result = left < right; break;
  254. case "<=": result = left <= right; break;
  255. case ">": result = left > right; break;
  256. case ">=": result = left >= right; break;
  257. default:
  258. return this;
  259. }
  260. if (isNaN(result) && compressor.find_parent(AST_With)) {
  261. // leave original expression as is
  262. return this;
  263. }
  264. return result;
  265. });
  266. def_eval(AST_Conditional, function (compressor, depth) {
  267. var condition = this.condition._eval(compressor, depth);
  268. if (condition === this.condition)
  269. return this;
  270. var node = condition ? this.consequent : this.alternative;
  271. var value = node._eval(compressor, depth);
  272. return value === node ? this : value;
  273. });
  274. // Set of AST_SymbolRef which are currently being evaluated.
  275. // Avoids infinite recursion of ._eval()
  276. const reentrant_ref_eval = new Set();
  277. def_eval(AST_SymbolRef, function (compressor, depth) {
  278. if (reentrant_ref_eval.has(this))
  279. return this;
  280. var fixed = this.fixed_value();
  281. if (!fixed)
  282. return this;
  283. reentrant_ref_eval.add(this);
  284. const value = fixed._eval(compressor, depth);
  285. reentrant_ref_eval.delete(this);
  286. if (value === fixed)
  287. return this;
  288. if (value && typeof value == "object") {
  289. var escaped = this.definition().escaped;
  290. if (escaped && depth > escaped)
  291. return this;
  292. }
  293. return value;
  294. });
  295. const global_objs = { Array, Math, Number, Object, String };
  296. const regexp_flags = new Set([
  297. "dotAll",
  298. "global",
  299. "ignoreCase",
  300. "multiline",
  301. "sticky",
  302. "unicode",
  303. ]);
  304. def_eval(AST_PropAccess, function (compressor, depth) {
  305. const obj = this.expression._eval(compressor, depth);
  306. if (obj === nullish || (this.optional && obj == null)) return nullish;
  307. if (compressor.option("unsafe")) {
  308. var key = this.property;
  309. if (key instanceof AST_Node) {
  310. key = key._eval(compressor, depth);
  311. if (key === this.property)
  312. return this;
  313. }
  314. var exp = this.expression;
  315. var val;
  316. if (is_undeclared_ref(exp)) {
  317. var aa;
  318. var first_arg = exp.name === "hasOwnProperty"
  319. && key === "call"
  320. && (aa = compressor.parent() && compressor.parent().args)
  321. && (aa && aa[0]
  322. && aa[0].evaluate(compressor));
  323. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  324. if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) {
  325. return this.clone();
  326. }
  327. if (!is_pure_native_value(exp.name, key))
  328. return this;
  329. val = global_objs[exp.name];
  330. } else {
  331. val = exp._eval(compressor, depth + 1);
  332. if (val instanceof RegExp) {
  333. if (key == "source") {
  334. return regexp_source_fix(val.source);
  335. } else if (key == "flags" || regexp_flags.has(key)) {
  336. return val[key];
  337. }
  338. }
  339. if (!val || val === exp || !HOP(val, key))
  340. return this;
  341. if (typeof val == "function")
  342. switch (key) {
  343. case "name":
  344. return val.node.name ? val.node.name.name : "";
  345. case "length":
  346. return val.node.length_property();
  347. default:
  348. return this;
  349. }
  350. }
  351. return val[key];
  352. }
  353. return this;
  354. });
  355. def_eval(AST_Chain, function (compressor, depth) {
  356. const evaluated = this.expression._eval(compressor, depth);
  357. return evaluated === nullish
  358. ? undefined
  359. : evaluated === this.expression
  360. ? this
  361. : evaluated;
  362. });
  363. def_eval(AST_Call, function (compressor, depth) {
  364. var exp = this.expression;
  365. const callee = exp._eval(compressor, depth);
  366. if (callee === nullish || (this.optional && callee == null)) return nullish;
  367. if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
  368. var key = exp.property;
  369. if (key instanceof AST_Node) {
  370. key = key._eval(compressor, depth);
  371. if (key === exp.property)
  372. return this;
  373. }
  374. var val;
  375. var e = exp.expression;
  376. if (is_undeclared_ref(e)) {
  377. var first_arg = e.name === "hasOwnProperty" &&
  378. key === "call" &&
  379. (this.args[0] && this.args[0].evaluate(compressor));
  380. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  381. if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) {
  382. return this.clone();
  383. }
  384. if (!is_pure_native_fn(e.name, key)) return this;
  385. val = global_objs[e.name];
  386. } else {
  387. val = e._eval(compressor, depth + 1);
  388. if (val === e || !val)
  389. return this;
  390. if (!is_pure_native_method(val.constructor.name, key))
  391. return this;
  392. }
  393. var args = [];
  394. for (var i = 0, len = this.args.length; i < len; i++) {
  395. var arg = this.args[i];
  396. var value = arg._eval(compressor, depth);
  397. if (arg === value)
  398. return this;
  399. if (arg instanceof AST_Lambda)
  400. return this;
  401. args.push(value);
  402. }
  403. try {
  404. return val[key].apply(val, args);
  405. } catch (ex) {
  406. // We don't really care
  407. }
  408. }
  409. return this;
  410. });
  411. // Also a subclass of AST_Call
  412. def_eval(AST_New, return_this);