IfStatementSimplifyTransformer.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import { inject, injectable, } from 'inversify';
  2. import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
  3. import * as ESTree from 'estree';
  4. import { IIfStatementSimplifyData } from '../../interfaces/node-transformers/minification-transformers/IIfStatementSimplifyData';
  5. import { IIfStatementIteratedStatementsData } from '../../interfaces/node-transformers/minification-transformers/IIfStatementIteratedStatementsData';
  6. import { IOptions } from '../../interfaces/options/IOptions';
  7. import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
  8. import { IVisitor } from '../../interfaces/node-transformers/IVisitor';
  9. import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage';
  10. import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
  11. import { NodeGuards } from '../../node/NodeGuards';
  12. import { NodeFactory } from '../../node/NodeFactory';
  13. /**
  14. * Simplifies `IfStatement` node
  15. */
  16. @injectable()
  17. export class IfStatementSimplifyTransformer extends AbstractNodeTransformer {
  18. /**
  19. * @param {IRandomGenerator} randomGenerator
  20. * @param {IOptions} options
  21. */
  22. public constructor (
  23. @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
  24. @inject(ServiceIdentifiers.IOptions) options: IOptions
  25. ) {
  26. super(randomGenerator, options);
  27. }
  28. /**
  29. * @param {NodeTransformationStage} nodeTransformationStage
  30. * @returns {IVisitor | null}
  31. */
  32. public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null {
  33. switch (nodeTransformationStage) {
  34. case NodeTransformationStage.Minification:
  35. return {
  36. leave: (
  37. node: ESTree.Node,
  38. parentNode: ESTree.Node | null
  39. ): ESTree.Node | undefined => {
  40. if (parentNode && NodeGuards.isIfStatementNode(node)) {
  41. return this.transformNode(node, parentNode);
  42. }
  43. }
  44. };
  45. default:
  46. return null;
  47. }
  48. }
  49. /**
  50. * @param {ESTree.IfStatement} ifStatementNode
  51. * @param {ESTree.Node} parentNode
  52. * @returns {ESTree.IfStatement}
  53. */
  54. public transformNode (
  55. ifStatementNode: ESTree.IfStatement,
  56. parentNode: ESTree.Node
  57. ): ESTree.Node {
  58. const consequentSimplifyData: IIfStatementSimplifyData | null = this.getIfStatementSimplifyData(ifStatementNode.consequent);
  59. // Variant #1: no valid consequent expression data
  60. if (!consequentSimplifyData) {
  61. return ifStatementNode;
  62. }
  63. // Variant #2: valid data for consequent expression only
  64. if (!ifStatementNode.alternate) {
  65. return this.getConsequentNode(ifStatementNode, consequentSimplifyData);
  66. }
  67. const alternateSimplifyData: IIfStatementSimplifyData | null = this.getIfStatementSimplifyData(ifStatementNode.alternate);
  68. if (!alternateSimplifyData) {
  69. return ifStatementNode;
  70. }
  71. // Variant #3: valid data for consequent and alternate expressions
  72. return this.getConsequentAndAlternateNode(ifStatementNode, consequentSimplifyData, alternateSimplifyData);
  73. }
  74. /**
  75. * @param {ESTree.IfStatement} ifStatementNode
  76. * @param {IIfStatementSimplifyData} consequentSimplifyData
  77. * @returns {ESTree.Node}
  78. */
  79. private getConsequentNode (
  80. ifStatementNode: ESTree.IfStatement,
  81. consequentSimplifyData: IIfStatementSimplifyData
  82. ): ESTree.Node {
  83. /**
  84. * Converts:
  85. * if (true) {
  86. * const foo = 1;
  87. * console.log(1);
  88. * return 1;
  89. * }
  90. *
  91. * to:
  92. * if (true) {
  93. * const foo = 1;
  94. * return console.log(1), 1;
  95. * }
  96. */
  97. if (
  98. consequentSimplifyData.leadingStatements.length
  99. || !consequentSimplifyData.trailingStatement
  100. ) {
  101. return NodeFactory.ifStatementNode(
  102. ifStatementNode.test,
  103. this.getPartialBlockStatementNode(consequentSimplifyData)
  104. );
  105. }
  106. /**
  107. * Converts:
  108. * if (true) {
  109. * return 1;
  110. * }
  111. *
  112. * to:
  113. * if (true)
  114. * return 1;
  115. */
  116. if (consequentSimplifyData.hasReturnStatement) {
  117. return NodeFactory.ifStatementNode(
  118. ifStatementNode.test,
  119. consequentSimplifyData.trailingStatement.statement
  120. );
  121. }
  122. /**
  123. * Converts:
  124. * if (true) {
  125. * console.log(1);
  126. * }
  127. *
  128. * to:
  129. * true && console.log(1);
  130. */
  131. return NodeFactory.expressionStatementNode(
  132. NodeFactory.logicalExpressionNode(
  133. '&&',
  134. ifStatementNode.test,
  135. consequentSimplifyData.trailingStatement.expression
  136. )
  137. );
  138. }
  139. /**
  140. * @param {ESTree.IfStatement} ifStatementNode
  141. * @param {IIfStatementSimplifyData} consequentSimplifyData
  142. * @param {IIfStatementSimplifyData} alternateSimplifyData
  143. * @returns {ESTree.Node}
  144. */
  145. private getConsequentAndAlternateNode (
  146. ifStatementNode: ESTree.IfStatement,
  147. consequentSimplifyData: IIfStatementSimplifyData,
  148. alternateSimplifyData: IIfStatementSimplifyData
  149. ): ESTree.Node {
  150. /**
  151. * Converts:
  152. * if (true) {
  153. * const foo = 1;
  154. * console.log(1);
  155. * return 1;
  156. * }
  157. *
  158. * to:
  159. * if (true) {
  160. * const foo = 1;
  161. * return console.log(1), 1;
  162. * }
  163. */
  164. if (
  165. consequentSimplifyData.leadingStatements.length
  166. || alternateSimplifyData.leadingStatements.length
  167. || !consequentSimplifyData.trailingStatement
  168. || !alternateSimplifyData.trailingStatement
  169. ) {
  170. return NodeFactory.ifStatementNode(
  171. ifStatementNode.test,
  172. this.getPartialBlockStatementNode(consequentSimplifyData),
  173. this.getPartialBlockStatementNode(alternateSimplifyData)
  174. );
  175. }
  176. /**
  177. * Converts:
  178. * if (true) {
  179. * return 1;
  180. * } else {
  181. * return 2;
  182. * }
  183. *
  184. * to:
  185. * return true ? 1 : 2;
  186. */
  187. if (consequentSimplifyData.hasReturnStatement && alternateSimplifyData.hasReturnStatement) {
  188. return NodeFactory.returnStatementNode(
  189. NodeFactory.conditionalExpressionNode(
  190. ifStatementNode.test,
  191. consequentSimplifyData.trailingStatement.expression,
  192. alternateSimplifyData.trailingStatement.expression
  193. )
  194. );
  195. }
  196. /**
  197. * Converts:
  198. * if (true) {
  199. * return 1;
  200. * } else {
  201. * console.log(2);
  202. * }
  203. *
  204. * to:
  205. * if (true)
  206. * return 1;
  207. * else
  208. * console.log(2);
  209. */
  210. if (consequentSimplifyData.hasReturnStatement || alternateSimplifyData.hasReturnStatement) {
  211. return NodeFactory.ifStatementNode(
  212. ifStatementNode.test,
  213. consequentSimplifyData.trailingStatement.statement,
  214. alternateSimplifyData.trailingStatement.statement
  215. );
  216. }
  217. /**
  218. * Converts:
  219. * if (true) {
  220. * console.log(1);
  221. * } else {
  222. * console.log(2);
  223. * }
  224. *
  225. * to:
  226. * true ? console.log(1) : console.log(2);
  227. */
  228. return NodeFactory.expressionStatementNode(
  229. NodeFactory.conditionalExpressionNode(
  230. ifStatementNode.test,
  231. consequentSimplifyData.trailingStatement.expression,
  232. alternateSimplifyData.trailingStatement.expression
  233. )
  234. );
  235. }
  236. /**
  237. * Returns IIfStatementSimplifyData based on `IfStatement` node body
  238. *
  239. * @param {ESTree.Statement | null | undefined} statementNode
  240. * @returns {IIfStatementSimplifyData | null}
  241. */
  242. private getIfStatementSimplifyData (
  243. statementNode: ESTree.Statement | null | undefined
  244. ): IIfStatementSimplifyData | null {
  245. if (!statementNode || !NodeGuards.isBlockStatementNode(statementNode)) {
  246. return null;
  247. }
  248. const {
  249. startIndex,
  250. unwrappedExpressions,
  251. hasReturnStatement
  252. } = this.collectIteratedStatementsData(statementNode);
  253. const leadingStatements: ESTree.Statement[] = this.getLeadingStatements(statementNode, startIndex);
  254. if (!unwrappedExpressions.length) {
  255. return {
  256. leadingStatements,
  257. trailingStatement: null,
  258. hasReturnStatement
  259. };
  260. }
  261. const hasSingleExpression: boolean = unwrappedExpressions.length === 1;
  262. const expression: ESTree.Expression = hasSingleExpression
  263. ? unwrappedExpressions[0]
  264. : NodeFactory.sequenceExpressionNode(unwrappedExpressions);
  265. const statement: ESTree.Statement = hasReturnStatement
  266. ? NodeFactory.returnStatementNode(expression)
  267. : NodeFactory.expressionStatementNode(expression);
  268. return {
  269. leadingStatements,
  270. trailingStatement: {
  271. statement,
  272. expression
  273. },
  274. hasReturnStatement
  275. };
  276. }
  277. /**
  278. * Iterates over `IfStatement` node body and collects data
  279. *
  280. * @param {ESTree.Statement | null | undefined} statementNode
  281. * @returns {IIfStatementIteratedStatementsData}
  282. */
  283. private collectIteratedStatementsData (
  284. statementNode: ESTree.BlockStatement
  285. ): IIfStatementIteratedStatementsData {
  286. const statementNodeBodyLength: number = statementNode.body.length;
  287. const unwrappedExpressions: ESTree.Expression[] = [];
  288. let hasReturnStatement: boolean = false;
  289. let startIndex: number | null = 0;
  290. for (let i = 0; i < statementNodeBodyLength; i++) {
  291. const statementBodyStatementNode: ESTree.Statement = statementNode.body[i];
  292. if (startIndex === null) {
  293. startIndex = i;
  294. }
  295. if (NodeGuards.isExpressionStatementNode(statementBodyStatementNode)) {
  296. unwrappedExpressions.push(statementBodyStatementNode.expression);
  297. continue;
  298. }
  299. if (
  300. NodeGuards.isReturnStatementNode(statementBodyStatementNode)
  301. && statementBodyStatementNode.argument
  302. ) {
  303. unwrappedExpressions.push(statementBodyStatementNode.argument);
  304. hasReturnStatement = true;
  305. continue;
  306. }
  307. startIndex = null;
  308. unwrappedExpressions.length = 0;
  309. }
  310. return {
  311. startIndex,
  312. unwrappedExpressions,
  313. hasReturnStatement
  314. };
  315. }
  316. /**
  317. * Returns leading statements for IIfStatementSimplifyData
  318. *
  319. * @param {ESTree.BlockStatement} statementNode
  320. * @param {number | null} startIndex
  321. * @returns {ESTree.Statement[]}
  322. */
  323. private getLeadingStatements (statementNode: ESTree.BlockStatement, startIndex: number | null): ESTree.Statement[] {
  324. // variant #1: no valid statements inside `IfStatement` are found
  325. if (startIndex === null) {
  326. return statementNode.body;
  327. }
  328. return startIndex === 0
  329. // variant #2: all statements inside `IfStatement` branch are valid
  330. ? []
  331. // variant #3: only last N statements inside `IfStatement` branch are valid
  332. : statementNode.body.slice(0, startIndex);
  333. }
  334. /**
  335. * @param {IIfStatementSimplifyData} ifStatementSimplifyData
  336. * @returns {ESTree.BlockStatement}
  337. */
  338. private getPartialBlockStatementNode (ifStatementSimplifyData: IIfStatementSimplifyData): ESTree.Statement {
  339. // variant #1: all statements inside `IfStatement` branch are valid
  340. if (!ifStatementSimplifyData.leadingStatements.length && ifStatementSimplifyData.trailingStatement) {
  341. return ifStatementSimplifyData.trailingStatement.statement;
  342. }
  343. // variant #2: only last N statements inside `IfStatement` branch are valid
  344. return NodeFactory.blockStatementNode([
  345. ...ifStatementSimplifyData.leadingStatements,
  346. ...ifStatementSimplifyData.trailingStatement ? [ifStatementSimplifyData.trailingStatement.statement] : []
  347. ]);
  348. }
  349. }