common.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. AST_Array,
  35. AST_Arrow,
  36. AST_BigInt,
  37. AST_BlockStatement,
  38. AST_Call,
  39. AST_Chain,
  40. AST_Class,
  41. AST_Const,
  42. AST_Constant,
  43. AST_DefClass,
  44. AST_Defun,
  45. AST_EmptyStatement,
  46. AST_Export,
  47. AST_False,
  48. AST_Function,
  49. AST_Import,
  50. AST_Infinity,
  51. AST_LabeledStatement,
  52. AST_Lambda,
  53. AST_Let,
  54. AST_LoopControl,
  55. AST_NaN,
  56. AST_Node,
  57. AST_Null,
  58. AST_Number,
  59. AST_Object,
  60. AST_ObjectKeyVal,
  61. AST_PropAccess,
  62. AST_RegExp,
  63. AST_Scope,
  64. AST_Sequence,
  65. AST_SimpleStatement,
  66. AST_Statement,
  67. AST_String,
  68. AST_SymbolRef,
  69. AST_True,
  70. AST_UnaryPrefix,
  71. AST_Undefined,
  72. TreeWalker,
  73. walk,
  74. walk_abort,
  75. walk_parent,
  76. } from "../ast.js";
  77. import { make_node, regexp_source_fix, string_template, makePredicate } from "../utils/index.js";
  78. import { first_in_statement } from "../utils/first_in_statement.js";
  79. import { has_flag, TOP } from "./compressor-flags.js";
  80. export function merge_sequence(array, node) {
  81. if (node instanceof AST_Sequence) {
  82. array.push(...node.expressions);
  83. } else {
  84. array.push(node);
  85. }
  86. return array;
  87. }
  88. export function make_sequence(orig, expressions) {
  89. if (expressions.length == 1) return expressions[0];
  90. if (expressions.length == 0) throw new Error("trying to create a sequence with length zero!");
  91. return make_node(AST_Sequence, orig, {
  92. expressions: expressions.reduce(merge_sequence, [])
  93. });
  94. }
  95. export function make_node_from_constant(val, orig) {
  96. switch (typeof val) {
  97. case "string":
  98. return make_node(AST_String, orig, {
  99. value: val
  100. });
  101. case "number":
  102. if (isNaN(val)) return make_node(AST_NaN, orig);
  103. if (isFinite(val)) {
  104. return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
  105. operator: "-",
  106. expression: make_node(AST_Number, orig, { value: -val })
  107. }) : make_node(AST_Number, orig, { value: val });
  108. }
  109. return val < 0 ? make_node(AST_UnaryPrefix, orig, {
  110. operator: "-",
  111. expression: make_node(AST_Infinity, orig)
  112. }) : make_node(AST_Infinity, orig);
  113. case "bigint":
  114. return make_node(AST_BigInt, orig, { value: val.toString() });
  115. case "boolean":
  116. return make_node(val ? AST_True : AST_False, orig);
  117. case "undefined":
  118. return make_node(AST_Undefined, orig);
  119. default:
  120. if (val === null) {
  121. return make_node(AST_Null, orig, { value: null });
  122. }
  123. if (val instanceof RegExp) {
  124. return make_node(AST_RegExp, orig, {
  125. value: {
  126. source: regexp_source_fix(val.source),
  127. flags: val.flags
  128. }
  129. });
  130. }
  131. throw new Error(string_template("Can't handle constant of type: {type}", {
  132. type: typeof val
  133. }));
  134. }
  135. }
  136. export function best_of_expression(ast1, ast2) {
  137. return ast1.size() > ast2.size() ? ast2 : ast1;
  138. }
  139. export function best_of_statement(ast1, ast2) {
  140. return best_of_expression(
  141. make_node(AST_SimpleStatement, ast1, {
  142. body: ast1
  143. }),
  144. make_node(AST_SimpleStatement, ast2, {
  145. body: ast2
  146. })
  147. ).body;
  148. }
  149. /** Find which node is smaller, and return that */
  150. export function best_of(compressor, ast1, ast2) {
  151. if (first_in_statement(compressor)) {
  152. return best_of_statement(ast1, ast2);
  153. } else {
  154. return best_of_expression(ast1, ast2);
  155. }
  156. }
  157. /** Simplify an object property's key, if possible */
  158. export function get_simple_key(key) {
  159. if (key instanceof AST_Constant) {
  160. return key.getValue();
  161. }
  162. if (key instanceof AST_UnaryPrefix
  163. && key.operator == "void"
  164. && key.expression instanceof AST_Constant) {
  165. return;
  166. }
  167. return key;
  168. }
  169. export function read_property(obj, key) {
  170. key = get_simple_key(key);
  171. if (key instanceof AST_Node) return;
  172. var value;
  173. if (obj instanceof AST_Array) {
  174. var elements = obj.elements;
  175. if (key == "length") return make_node_from_constant(elements.length, obj);
  176. if (typeof key == "number" && key in elements) value = elements[key];
  177. } else if (obj instanceof AST_Object) {
  178. key = "" + key;
  179. var props = obj.properties;
  180. for (var i = props.length; --i >= 0;) {
  181. var prop = props[i];
  182. if (!(prop instanceof AST_ObjectKeyVal)) return;
  183. if (!value && props[i].key === key) value = props[i].value;
  184. }
  185. }
  186. return value instanceof AST_SymbolRef && value.fixed_value() || value;
  187. }
  188. export function has_break_or_continue(loop, parent) {
  189. var found = false;
  190. var tw = new TreeWalker(function(node) {
  191. if (found || node instanceof AST_Scope) return true;
  192. if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop) {
  193. return found = true;
  194. }
  195. });
  196. if (parent instanceof AST_LabeledStatement) tw.push(parent);
  197. tw.push(loop);
  198. loop.body.walk(tw);
  199. return found;
  200. }
  201. // we shouldn't compress (1,func)(something) to
  202. // func(something) because that changes the meaning of
  203. // the func (becomes lexical instead of global).
  204. export function maintain_this_binding(parent, orig, val) {
  205. if (requires_sequence_to_maintain_binding(parent, orig, val)) {
  206. const zero = make_node(AST_Number, orig, { value: 0 });
  207. return make_sequence(orig, [ zero, val ]);
  208. } else {
  209. return val;
  210. }
  211. }
  212. /** Detect (1, x.noThis)(), (0, eval)(), which need sequences */
  213. export function requires_sequence_to_maintain_binding(parent, orig, val) {
  214. return (
  215. parent instanceof AST_UnaryPrefix && parent.operator == "delete"
  216. || parent instanceof AST_Call && parent.expression === orig
  217. && (
  218. val instanceof AST_Chain
  219. || val instanceof AST_PropAccess
  220. || val instanceof AST_SymbolRef && val.name == "eval"
  221. )
  222. );
  223. }
  224. export function is_func_expr(node) {
  225. return node instanceof AST_Arrow || node instanceof AST_Function;
  226. }
  227. /**
  228. * Used to determine whether the node can benefit from negation.
  229. * Not the case with arrow functions (you need an extra set of parens). */
  230. export function is_iife_call(node) {
  231. if (node.TYPE != "Call") return false;
  232. return node.expression instanceof AST_Function || is_iife_call(node.expression);
  233. }
  234. export function is_empty(thing) {
  235. if (thing === null) return true;
  236. if (thing instanceof AST_EmptyStatement) return true;
  237. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  238. return false;
  239. }
  240. export const identifier_atom = makePredicate("Infinity NaN undefined");
  241. export function is_identifier_atom(node) {
  242. return node instanceof AST_Infinity
  243. || node instanceof AST_NaN
  244. || node instanceof AST_Undefined;
  245. }
  246. /** Check if this is a SymbolRef node which has one def of a certain AST type */
  247. export function is_ref_of(ref, type) {
  248. if (!(ref instanceof AST_SymbolRef)) return false;
  249. var orig = ref.definition().orig;
  250. for (var i = orig.length; --i >= 0;) {
  251. if (orig[i] instanceof type) return true;
  252. }
  253. }
  254. /**Can we turn { block contents... } into just the block contents ?
  255. * Not if one of these is inside.
  256. **/
  257. export function can_be_evicted_from_block(node) {
  258. return !(
  259. node instanceof AST_DefClass ||
  260. node instanceof AST_Defun ||
  261. node instanceof AST_Let ||
  262. node instanceof AST_Const ||
  263. node instanceof AST_Export ||
  264. node instanceof AST_Import
  265. );
  266. }
  267. export function as_statement_array(thing) {
  268. if (thing === null) return [];
  269. if (thing instanceof AST_BlockStatement) return thing.body;
  270. if (thing instanceof AST_EmptyStatement) return [];
  271. if (thing instanceof AST_Statement) return [ thing ];
  272. throw new Error("Can't convert thing to statement array");
  273. }
  274. export function is_reachable(scope_node, defs) {
  275. const find_ref = node => {
  276. if (node instanceof AST_SymbolRef && defs.includes(node.definition())) {
  277. return walk_abort;
  278. }
  279. };
  280. return walk_parent(scope_node, (node, info) => {
  281. if (node instanceof AST_Scope && node !== scope_node) {
  282. var parent = info.parent();
  283. if (
  284. parent instanceof AST_Call
  285. && parent.expression === node
  286. // Async/Generators aren't guaranteed to sync evaluate all of
  287. // their body steps, so it's possible they close over the variable.
  288. && !(node.async || node.is_generator)
  289. ) {
  290. return;
  291. }
  292. if (walk(node, find_ref)) return walk_abort;
  293. return true;
  294. }
  295. });
  296. }
  297. /** Check if a ref refers to the name of a function/class it's defined within */
  298. export function is_recursive_ref(compressor, def) {
  299. var node;
  300. for (var i = 0; node = compressor.parent(i); i++) {
  301. if (node instanceof AST_Lambda || node instanceof AST_Class) {
  302. var name = node.name;
  303. if (name && name.definition() === def) {
  304. return true;
  305. }
  306. }
  307. }
  308. return false;
  309. }
  310. // TODO this only works with AST_Defun, shouldn't it work for other ways of defining functions?
  311. export function retain_top_func(fn, compressor) {
  312. return compressor.top_retain
  313. && fn instanceof AST_Defun
  314. && has_flag(fn, TOP)
  315. && fn.name
  316. && compressor.top_retain(fn.name.definition());
  317. }