native-objects.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 { AST_Array, AST_Dot, AST_New, AST_Number, AST_SymbolRef } from "../ast.js";
  34. import { makePredicate } from "../utils/index.js";
  35. import { is_undeclared_ref } from "./inference.js";
  36. // Lists of native methods, useful for `unsafe` option which assumes they exist.
  37. // Note: Lots of methods and functions are missing here, in case they aren't pure
  38. // or not available in all JS environments.
  39. const make_nested_lookup = (feature_callback) => (compressor) => {
  40. const obj = feature_callback(feature_variables(compressor));
  41. const out = new Map();
  42. for (var key of Object.keys(obj)) {
  43. if (obj[key]) {
  44. out.set(key, makePredicate(remove_false(obj[key])));
  45. }
  46. }
  47. const does_have = (global_name, fname) => {
  48. const inner_map = out.get(global_name);
  49. return inner_map != null && inner_map.has(fname);
  50. };
  51. return does_have;
  52. };
  53. const make_lookup = (feature_callback) => (compressor) => {
  54. const obj = feature_callback(feature_variables(compressor));
  55. const predicate = makePredicate(remove_false(obj));
  56. const does_have = (global_name) => {
  57. return predicate.has(global_name);
  58. };
  59. return does_have;
  60. };
  61. function remove_false(arr) {
  62. for (let i = 0; i < arr.length; i++) {
  63. if (arr[i] === false) {
  64. arr.splice(i, 1);
  65. i--;
  66. }
  67. }
  68. return arr;
  69. }
  70. /** Generate the object with arguments seen below */
  71. function feature_variables(compressor) {
  72. return {
  73. sloppy: compressor.option("unsafe"),
  74. es: compressor.option("builtins_ecma"),
  75. };
  76. }
  77. // eslint-disable-next-line no-unused-vars
  78. export const pure_access_globals = make_lookup(({ sloppy, es }) => [
  79. "Array",
  80. "Boolean",
  81. "clearInterval",
  82. "clearTimeout",
  83. "console",
  84. "Date",
  85. "decodeURI",
  86. "decodeURIComponent",
  87. "encodeURI",
  88. "encodeURIComponent",
  89. "Error",
  90. "escape",
  91. "eval",
  92. "EvalError",
  93. "Function",
  94. es >= 2020 && "globalThis",
  95. "isFinite",
  96. "isNaN",
  97. "JSON",
  98. "Math",
  99. "Number",
  100. "parseFloat",
  101. "parseInt",
  102. "RangeError",
  103. "ReferenceError",
  104. "RegExp",
  105. "Object",
  106. "setInterval",
  107. "setTimeout",
  108. "String",
  109. "SyntaxError",
  110. "TypeError",
  111. "unescape",
  112. "URIError",
  113. ]);
  114. // Objects which are safe to access without throwing or causing a side effect.
  115. // Usually we'd check the `unsafe` option first but these are way too common for that
  116. export const pure_prop_access_globals = new Set([
  117. "Number",
  118. "String",
  119. "Array",
  120. "Object",
  121. "Function",
  122. "Promise",
  123. ]);
  124. // eslint-disable-next-line no-unused-vars
  125. export const is_pure_native_fn = make_lookup(({ sloppy, es }) => [
  126. sloppy && es >= 2021 && "AggregateError",
  127. "Array",
  128. "ArrayBuffer",
  129. es >= 2020 && "BigInt",
  130. es >= 2020 && "BigInt64Array",
  131. es >= 2020 && "BigUint64Array",
  132. "Boolean",
  133. "Date",
  134. sloppy && "decodeURI",
  135. sloppy && "decodeURIComponent",
  136. sloppy && "encodeURI",
  137. sloppy && "encodeURIComponent",
  138. "Error",
  139. "escape",
  140. "EvalError",
  141. es >= 2021 && "FinalizationRegistry",
  142. es >= 2026 && "Float16Array",
  143. "Float32Array",
  144. "Float64Array",
  145. "Int16Array",
  146. "Int32Array",
  147. "Int8Array",
  148. "isFinite",
  149. "isNaN",
  150. es >= 2026 && "Iterator",
  151. es >= 2015 && "Map",
  152. "Number",
  153. "parseFloat",
  154. "parseInt",
  155. es >= 2015 && "Promise",
  156. es >= 2015 && "Proxy",
  157. "RangeError",
  158. "ReferenceError",
  159. sloppy && "RegExp",
  160. es >= 2015 && "Set",
  161. "String",
  162. es >= 2015 && "Symbol",
  163. "SyntaxError",
  164. "TypeError",
  165. "Uint16Array",
  166. "Uint32Array",
  167. "Uint8Array",
  168. "Uint8ClampedArray",
  169. sloppy && "unescape",
  170. "URIError",
  171. sloppy && es >= 2015 && "WeakMap",
  172. sloppy && es >= 2021 && "WeakRef",
  173. sloppy && es >= 2015 && "WeakSet",
  174. ]);
  175. const arg1_is_iterable = new Set([
  176. "Map",
  177. "Set",
  178. "WeakMap",
  179. "WeakSet",
  180. ]);
  181. const arg1_is_range_or_iterable = new Set([
  182. "ArrayBuffer",
  183. "Float32Array",
  184. "Float64Array",
  185. "Int16Array",
  186. "Int32Array",
  187. "Int8Array",
  188. "Uint16Array",
  189. "Uint32Array",
  190. "Uint8Array",
  191. "Uint8ClampedArray",
  192. ]);
  193. const lone_arg_is_range = new Set(["Array"]);
  194. const object_methods = [
  195. "constructor",
  196. "toString",
  197. "valueOf",
  198. ];
  199. // eslint-disable-next-line no-unused-vars
  200. export const is_pure_native_method = make_nested_lookup(({ sloppy, es }) => ({
  201. Array: [
  202. es >= 2022 && "at",
  203. es >= 2019 && "flat",
  204. es >= 2016 && "includes",
  205. "indexOf",
  206. "join",
  207. "lastIndexOf",
  208. "slice",
  209. ...object_methods,
  210. ],
  211. Boolean: object_methods,
  212. Function: object_methods,
  213. Number: [
  214. "toExponential",
  215. "toFixed",
  216. "toPrecision",
  217. ...object_methods,
  218. ],
  219. Object: object_methods,
  220. RegExp: [
  221. "test",
  222. ...object_methods,
  223. ],
  224. String: [
  225. es >= 2022 && "at",
  226. "charAt",
  227. "charCodeAt",
  228. es >= 2015 && "codePointAt",
  229. "concat",
  230. es >= 2025 && "endsWith",
  231. es >= 2015 && "includes",
  232. "indexOf",
  233. "italics",
  234. "lastIndexOf",
  235. es >= 2020 && "localeCompare",
  236. "match",
  237. es >= 2020 && "matchAll",
  238. es >= 2015 && "normalize",
  239. es >= 2017 && "padStart",
  240. es >= 2017 && "padEnd",
  241. es >= 2015 && sloppy && "repeat",
  242. "replace",
  243. es >= 2021 && "replaceAll",
  244. "search",
  245. "slice",
  246. "split",
  247. es >= 2015 && "startsWith",
  248. "substr",
  249. "substring",
  250. es >= 2015 && "repeat",
  251. "toLocaleLowerCase",
  252. "toLocaleUpperCase",
  253. "toLowerCase",
  254. "toUpperCase",
  255. "trim",
  256. es >= 2019 && "trimEnd",
  257. es >= 2019 && "trimStart",
  258. es >= 2019 && "trimLeft",
  259. es >= 2019 && "trimRight",
  260. ...object_methods,
  261. ],
  262. }));
  263. // eslint-disable-next-line no-unused-vars
  264. export const is_pure_native_static_fn = make_nested_lookup(({ sloppy, es }) => ({
  265. Array: [
  266. "isArray",
  267. es >= 2015 && "of",
  268. ],
  269. ArrayBuffer: [
  270. "isView",
  271. ],
  272. BigInt: es >= 2020 && [
  273. sloppy && "asIntN",
  274. sloppy && "asUintN",
  275. ],
  276. BigInt64Array: sloppy && es >= 2020 && ["of"],
  277. BigUint64Array: sloppy && es >= 2020 && ["of"],
  278. Date: [
  279. "now",
  280. "parse",
  281. "UTC",
  282. ],
  283. Error: [
  284. es >= 2026 && "isError",
  285. ],
  286. Float16Array: sloppy && es >= 2026 && ["of"],
  287. Float32Array: sloppy && ["of"],
  288. Float64Array: sloppy && ["of"],
  289. Int16Array: sloppy && ["of"],
  290. Int32Array: sloppy && ["of"],
  291. Int8Array: sloppy && ["of"],
  292. Math: [
  293. "abs",
  294. "acos",
  295. es >= 2015 && "acosh",
  296. "asin",
  297. es >= 2015 && "asinh",
  298. "atan",
  299. "atan2",
  300. es >= 2015 && "atanh",
  301. es >= 2015 && "cbrt",
  302. "ceil",
  303. es >= 2015 && "clz32",
  304. "cos",
  305. es >= 2015 && "cosh",
  306. "exp",
  307. es >= 2015 && "expm1",
  308. "floor",
  309. es >= 2026 && "f16round",
  310. es >= 2015 && "fround",
  311. es >= 2015 && "hypot",
  312. es >= 2015 && "imul",
  313. "log",
  314. es >= 2015 && "log10",
  315. es >= 2015 && "log1p",
  316. es >= 2015 && "log2",
  317. "max",
  318. "min",
  319. "pow",
  320. "round",
  321. es >= 2015 && "sign",
  322. "sin",
  323. es >= 2015 && "sinh",
  324. "sqrt",
  325. "tan",
  326. es >= 2015 && "tanh",
  327. es >= 2015 && "trunc",
  328. ],
  329. Number: [
  330. es >= 2015 && "isFinite",
  331. es >= 2015 && "isInteger",
  332. es >= 2015 && "isSafeInteger",
  333. es >= 2015 && "isNaN",
  334. es >= 2015 && "parseFloat",
  335. es >= 2015 && "parseInt",
  336. ],
  337. Object: [
  338. sloppy && "create",
  339. sloppy && "getOwnPropertyDescriptor",
  340. es >= 2017 && sloppy && "getOwnPropertyDescriptors",
  341. sloppy && "getOwnPropertyNames",
  342. es >= 2015 && sloppy && "getOwnPropertySymbols",
  343. sloppy && "getPrototypeOf",
  344. es >= 2022 && sloppy && "hasOwn",
  345. es >= 2015 && "is",
  346. "isExtensible",
  347. "isFrozen",
  348. "isSealed",
  349. es >= 2015 && sloppy && "keys",
  350. ],
  351. Promise: es >= 2015 && [
  352. es >= 2024 && "withResolvers",
  353. ],
  354. Proxy: es >= 2015 && [
  355. sloppy && "revocable",
  356. ],
  357. Reflect: es >= 2015 && [
  358. sloppy && "has",
  359. sloppy && "isExtensible",
  360. sloppy && "ownKeys",
  361. ],
  362. RegExp: [
  363. es >= 2026 && sloppy && "escape",
  364. ],
  365. String: [
  366. "fromCharCode",
  367. sloppy && es >= 2025 && "fromCodePoint",
  368. ],
  369. Uint16Array: ["of"],
  370. Uint32Array: ["of"],
  371. Uint8Array: ["of"],
  372. Uint8ClampedArray: ["of"],
  373. }));
  374. // Known numeric values which come with JS environments
  375. // eslint-disable-next-line no-unused-vars
  376. export const is_pure_native_static_property = make_nested_lookup(({ sloppy, es }) => ({
  377. Math: [
  378. "E",
  379. "LN10",
  380. "LN2",
  381. "LOG2E",
  382. "LOG10E",
  383. "PI",
  384. "SQRT1_2",
  385. "SQRT2",
  386. ],
  387. Number: [
  388. es >= 2015 && "EPSILON",
  389. es >= 2015 && "MAX_SAFE_VALUE",
  390. "MAX_VALUE",
  391. es >= 2015 && "MIN_SAFE_VALUE",
  392. "MIN_VALUE",
  393. "NaN",
  394. "NEGATIVE_INFINITY",
  395. "POSITIVE_INFINITY",
  396. ],
  397. RegExp: [
  398. "$_",
  399. "$0",
  400. "$1",
  401. "$2",
  402. "$3",
  403. "$4",
  404. "$5",
  405. "$6",
  406. "$7",
  407. "$8",
  408. "$9",
  409. "input",
  410. "lastMatch",
  411. "lastParen",
  412. "leftContext",
  413. "rightContext",
  414. ],
  415. }));
  416. const re_uppercase_first_letter = /^[A-Z]/;
  417. export function is_pure_builtin_call(compressor, call) {
  418. let builtin = "";
  419. let method = "";
  420. let exp = call.expression;
  421. if (is_undeclared_ref(exp)) {
  422. builtin = exp.name;
  423. } else if (exp instanceof AST_Dot) {
  424. method = exp.property;
  425. exp = exp.expression;
  426. if (is_undeclared_ref(exp)) {
  427. if (
  428. // globalThis.pureFunc()
  429. exp.name === "globalThis"
  430. && compressor.option("builtins_ecma") >= 2020
  431. ) {
  432. builtin = method;
  433. method = "";
  434. } else {
  435. // SomeBuiltin.pureFunc()
  436. builtin = exp.name;
  437. }
  438. } else if (exp instanceof AST_Dot) {
  439. if (
  440. is_undeclared_ref(exp.expression)
  441. && exp.expression.name === "globalThis"
  442. && compressor.option("builtins_ecma") >= 2020
  443. ) {
  444. // globalThis.SomeBuiltin.pureFunc()
  445. builtin = exp.property;
  446. } else {
  447. return false;
  448. }
  449. } else {
  450. return false;
  451. }
  452. } else {
  453. return false;
  454. }
  455. if (!method) {
  456. if (compressor.is_pure_native_fn(builtin)) {
  457. // some require `new`, others throw if you use it
  458. const is_new = call instanceof AST_New;
  459. const should_be_new = re_uppercase_first_letter.test(builtin); // true of all `is_pure_native_fn`
  460. if (is_new !== should_be_new) return false;
  461. if (!is_builtin_pure_with_these_args(builtin, call.args)) {
  462. return false;
  463. }
  464. return true;
  465. }
  466. return false;
  467. } else {
  468. return compressor.is_pure_native_static_fn(builtin, method);
  469. }
  470. }
  471. /** Some builtins are listed above but their purity is subject to some conditions */
  472. function is_builtin_pure_with_these_args(builtin, args) {
  473. // all the builtins we deal with here are ok with getting 0 args
  474. if (args.length === 0) return true;
  475. let arg1 = args[0];
  476. if (arg1 instanceof AST_SymbolRef) {
  477. arg1 = arg1.fixed_value();
  478. }
  479. if (lone_arg_is_range.has(builtin)) { // new Array(number)
  480. const arg_valid = args.length > 1
  481. || arg1 instanceof AST_Number
  482. && arg1.value >= 0 && arg1.value <= 0xffffffff;
  483. // TODO: or, we are asked to ignore TypeError
  484. if (!arg_valid) return false;
  485. }
  486. if (arg1_is_range_or_iterable.has(builtin)) { // new Float32Array(number | Array)
  487. const arg_valid = args.length === 0
  488. || arg1 instanceof AST_Array
  489. || arg1 instanceof AST_Number
  490. && arg1.value >= 0 && arg1.value <= 0xffffffff;
  491. if (!arg_valid) return false;
  492. }
  493. if (arg1_is_iterable.has(builtin)) { // new Set(iterable)
  494. const arg_valid = args.length === 0 || arg1 instanceof AST_Array;
  495. if (!arg_valid) return false;
  496. }
  497. return true;
  498. }