Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
196 changes: 196 additions & 0 deletions packages/babel-helper-evaluate-path/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,37 @@
"use strict";

module.exports = function evaluate(path) {
if (path.isReferencedIdentifier()) {
return evaluateIdentifier(path);
}

const state = {
confident: true
};

// prepare
path.traverse({
Scope(scopePath) {
scopePath.skip();
},
ReferencedIdentifier(idPath) {
const binding = idPath.scope.getBinding(idPath.node.name);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can remove this as well. evaluate identifier takes care of this already.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is required as well. For babel's evaluate to take care of globals. Here we ignore globals. In evaluatePath we depot it. If a referencedId makes it to evaluateId, we have to deopt instead of simply ignoring it. Though that code looks like it's never reached, it will be useful for detecting side-effects from other transformations.

// don't deopt globals
// let babel take care of it
if (!binding) return;

const evalResult = evaluateIdentifier(idPath);
if (!evalResult.confident) {
state.confident = evalResult.confident;
state.deoptPath = evalResult.deoptPath;
}
}
});

if (!state.confident) {
return state;
}

try {
return path.evaluate();
} catch (e) {
Expand All @@ -8,3 +41,166 @@ module.exports = function evaluate(path) {
};
}
};

// Original Source:
// https://github.com/babel/babel/blob/master/packages/babel-traverse/src/path/evaluation.js
// modified for Babili use
function evaluateIdentifier(path) {
if (!path.isReferencedIdentifier()) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check can be removed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will help in catching bugs where the refId path is replaced with something else. This has been an issue in DCE+mangle previously.

throw new Error(`Expected ReferencedIdentifier. Got ${path.type}`);
}

const { node } = path;

const binding = path.scope.getBinding(node.name);

if (!binding) {
return deopt(path);
}

if (binding.constantViolations.length > 0) {
return deopt(binding.path);
}

// referenced in a different scope - deopt
if (shouldDeoptBasedOnScope(binding, path)) {
return deopt(path);
}

// let/var/const referenced before init
// or "var" referenced in an outer scope
const flowEvalResult = evaluateBasedOnControlFlow(binding, path);

if (flowEvalResult.confident) {
return flowEvalResult;
}

if (flowEvalResult.shouldDeopt) {
return deopt(path);
}

return path.evaluate();
}

// check if referenced in a different fn scope
// we can't determine if this function is called sync or async
// if the binding is in program scope
// all it's references inside a different function should be deopted
function shouldDeoptBasedOnScope(binding, refPath) {
if (binding.scope.path.isProgram() && refPath.scope !== binding.scope) {
return true;
}
return false;
}

function evaluateBasedOnControlFlow(binding, refPath) {
if (binding.kind === "var") {
// early-exit
const declaration = binding.path.parentPath;
if (
declaration.parentPath.isIfStatement() ||
declaration.parentPath.isLoop() ||
declaration.parentPath.isSwitchCase()
) {
return { shouldDeopt: true };
}

let blockParent = binding.path.scope.getBlockParent().path;
const fnParent = binding.path.getFunctionParent();

if (blockParent === fnParent) {
if (!fnParent.isProgram()) blockParent = blockParent.get("body");
}

// detect Usage Outside Init Scope
if (!blockParent.get("body").some(stmt => stmt.isAncestor(refPath))) {
return { shouldDeopt: true };
}

// Detect usage before init
const stmts = fnParent.isProgram()
? fnParent.get("body")
: fnParent.get("body").get("body");

const compareResult = compareBindingAndReference({
binding,
refPath,
stmts
});

if (compareResult.reference && compareResult.binding) {
if (
compareResult.reference.scope === "current" &&
compareResult.reference.idx < compareResult.binding.idx
) {
return { confident: true, value: void 0 };
}

return { shouldDeopt: true };
}
} else if (binding.kind === "let" || binding.kind === "const") {
// binding.path is the declarator
const declarator = binding.path;
let scopePath = declarator.scope.path;
if (scopePath.isFunction()) {
scopePath = scopePath.get("body");
}

// Detect Usage before Init
const stmts = scopePath.get("body");

const compareResult = compareBindingAndReference({
binding,
refPath,
stmts
});

if (compareResult.reference && compareResult.binding) {
if (
compareResult.reference.scope === "current" &&
compareResult.reference.idx < compareResult.binding.idx
) {
throw new Error(
`ReferenceError: Used ${refPath.node.name}: ` +
`${binding.kind} binding before declaration`
);
}
if (compareResult.reference.scope === "other") {
return { shouldDeopt: true };
}
}
}

return { confident: false, shouldDeopt: false };
}

function compareBindingAndReference({ binding, refPath, stmts }) {
const state = {
binding: null,
reference: null
};

for (const [idx, stmt] of stmts.entries()) {
if (stmt.isAncestor(binding.path)) {
state.binding = { idx };
}
for (const ref of binding.referencePaths) {
if (ref === refPath && stmt.isAncestor(ref)) {
state.reference = {
idx,
scope: binding.path.scope === ref.scope ? "current" : "other"
};
break;
}
}
}

return state;
}

function deopt(deoptPath) {
return {
confident: false,
deoptPath
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ new A();",
exports[`minify-builtins should collect and minify no matter any depth 1`] = `
Object {
"_source": "function a (){
Math.max(b, a);
Math.max(c, a);
const b = () => {
const a = Math.floor(c);
Math.min(b, a) * Math.floor(b);
Expand All @@ -95,7 +95,7 @@ Object {
}
}",
"expected": "function a() {
Math.max(b, a);
Math.max(c, a);
const b = () => {
var _Mathmin = Math.min;
var _Mathfloor = Math.floor;
Expand Down Expand Up @@ -170,8 +170,8 @@ exports[`minify-builtins should minify builtins to method scope for class declar
Object {
"_source": "class Test {
foo() {
Math.max(c, d)
Math.max(c, d)
Math.max(a, d)
Math.max(a, d)
const c = function() {
Math.max(c, d)
Math.floor(m);
Expand All @@ -187,8 +187,8 @@ Object {
foo() {
var _Mathmax = Math.max;

_Mathmax(c, d);
_Mathmax(c, d);
_Mathmax(a, d);
_Mathmax(a, d);
const c = function () {
var _Mathfloor = Math.floor;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe("minify-builtins", () => {
"should collect and minify no matter any depth",
`
function a (){
Math.max(b, a);
Math.max(c, a);
const b = () => {
const a = Math.floor(c);
Math.min(b, a) * Math.floor(b);
Expand Down Expand Up @@ -68,8 +68,8 @@ describe("minify-builtins", () => {
`
class Test {
foo() {
Math.max(c, d)
Math.max(c, d)
Math.max(a, d)
Math.max(a, d)
const c = function() {
Math.max(c, d)
Math.floor(m);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -518,59 +518,41 @@ describe("dce-plugin", () => {
);

thePlugin(
"should handle orpahaned returns",
"should handle orphaned returns",
`
var a = true;
function foo() {
if (a) return;
x();
}
`,
var a = true;
function foo() {
if (a) return;
x();
}
`
var a = true;
function foo() {}
`
);

thePlugin(
"should handle orpahaned returns with a value",
`
var a = true;
function foo() {
if (a) return 1;
x();
}
`,
var a = true;
function foo() {
if (a) return 1;
x();
}
`
var a = true;
function foo() {
return 1;
}
`
);

thePlugin(
"should handle orphaned, redundant returns",
`
var x = true;
function foo() {
if (b) {
if (x) {
z();
return;
var x = true;
function foo() {
if (b) {
if (x) {
z();
return;
}
y();
}
y();
}
}
`,
`
var x = true;
function foo() {
if (b) {
z();
}
}
`
);

thePlugin(
Expand Down Expand Up @@ -2472,4 +2454,35 @@ describe("dce-plugin", () => {
}
`
);

thePlugin.skip(
"should optimize to void 0 for lets referenced before init declarations",
`
function foo() {
bar(a); // Should be a ReferenceError
let a = 1;
}
`
);

thePlugin(
"should optimize lets referenced before init declarations - 2",
`
function foo() {
function bar() {
if (a) console.log(a);
}
let a = 1;
return bar;
}
`,
`
function foo() {
let a = 1;
return function () {
if (a) console.log(a);
};
}
`
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
"author": "amasad",
"license": "MIT",
"main": "lib/index.js",
"keywords": [
"babel-plugin"
],
"keywords": ["babel-plugin"],
"dependencies": {
"babel-helper-evaluate-path": "^0.1.0",
"babel-helper-mark-eval-scopes": "^0.1.1",
"babel-helper-remove-or-void": "^0.1.1",
"lodash.some": "^4.6.0"
Expand Down
Loading