common.js 11 KB

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