实现目的:return简写表达式还原,增强可读性
处理前 demo.js
function _0x30e2() {
return a = 1, b = 2, c = 3, d = 4, a + b + c + d;
}
console.log(_0x30e2());
处理后 demoNew.js
function _0x30e2() {
a = 1, b = 2, c = 3, d = 4;
return a + b + c + d;
}
console.log(_0x30e2());
主逻辑源码 ObDecryFuMain.js
const fs = require("fs");//文件读写
const parse = require("@babel/parser"); //解析为ast
const traverse = require('@babel/traverse').default;//遍历节点
const t = require('@babel/types');//类型
const generator = require('@babel/generator').default;//ast解析为代码
//读取js文件
const jscode = fs.readFileSync(
'./demo.js', {
encoding: 'utf-8'
}
);
let ast = parse.parse(jscode);//js转ast
function remove_return_comma(path) {
// return简写表达式还原
let pathargument = path.node.argument;
if (!t.isSequenceExpression(pathargument))
return;
//获取数组的长度
let arglength = path.node.argument.expressions.length;
//数组填充
let body = []
for (i = 0; i < arglength - 1; i++) {
//自执行特殊处理
if (t.isCallExpression(path.node.argument.expressions[i])) {
if (!t.isFunctionExpression(path.node.argument.expressions[i].callee)) return;
let callee = path.node.argument.expressions[i].callee;
if (!callee.id) {
body[i] = t.identifier('!' + generator(path.node.argument.expressions[i]).code + ';');
} else {
body[i] = t.identifier(generator(path.node.argument.expressions[i]).code + ';');
}
} else {
body[i] = t.identifier(generator(path.node.argument.expressions[i]).code + ';');
}
}
//数组最后一个为return语句
body[arglength - 1] = t.ReturnStatement(path.node.argument.expressions[arglength - 1]);
//节点替换
path.replaceInline(body)
}
traverse(ast, {ReturnStatement: {exit: [remove_return_comma]},}); // 序列表达式还原
let {code} = generator(ast,opts = {jsescOption:{"minimal":true}})
//文件保存
fs.writeFile('./demoNew.js', code, (err) => {
});