* Eliminate an unused statement. * @param {JavascriptParser} parser the parser * @param {Statement} statement the statement to remove * @param {boolean} alwaysInBlock whether to always generate curly brackets * @returns {void}
(parser, statement, alwaysInBlock)
| 517 | * @returns {void} |
| 518 | */ |
| 519 | eliminateUnusedStatement(parser, statement, alwaysInBlock) { |
| 520 | // Before removing the unused branch, the hoisted declarations |
| 521 | // must be collected. |
| 522 | // |
| 523 | // Given the following code: |
| 524 | // |
| 525 | // if (true) f() else g() |
| 526 | // if (false) { |
| 527 | // function f() {} |
| 528 | // const g = function g() {} |
| 529 | // if (someTest) { |
| 530 | // let a = 1 |
| 531 | // var x, {y, z} = obj |
| 532 | // } |
| 533 | // } else { |
| 534 | // … |
| 535 | // } |
| 536 | // |
| 537 | // the generated code is: |
| 538 | // |
| 539 | // if (true) f() else {} |
| 540 | // if (false) { |
| 541 | // var f, x, y, z; (in loose mode) |
| 542 | // var x, y, z; (in strict mode) |
| 543 | // } else { |
| 544 | // … |
| 545 | // } |
| 546 | // |
| 547 | // NOTE: When code runs in strict mode, `var` declarations |
| 548 | // are hoisted but `function` declarations don't. |
| 549 | // |
| 550 | const declarations = parser.scope.isStrict |
| 551 | ? getHoistedDeclarations(statement, false) |
| 552 | : getHoistedDeclarations(statement, true); |
| 553 | |
| 554 | const inBlock = alwaysInBlock || statement.type === "BlockStatement"; |
| 555 | |
| 556 | let replacement = inBlock ? "{" : ""; |
| 557 | replacement += |
| 558 | declarations.length > 0 ? ` var ${declarations.join(", ")}; ` : ""; |
| 559 | replacement += inBlock ? "}" : ""; |
| 560 | |
| 561 | const dep = new ConstDependency( |
| 562 | `// removed by dead control flow\n${replacement}`, |
| 563 | /** @type {Range} */ (statement.range) |
| 564 | ); |
| 565 | dep.loc = /** @type {SourceLocation} */ (statement.loc); |
| 566 | parser.state.module.addPresentationalDependency(dep); |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | module.exports = ConstPlugin; |
no test coverage detected