evaluate.js 15 KB

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