55 lines
1.5 KiB
JavaScript
55 lines
1.5 KiB
JavaScript
//@Author : dingjiawen
|
||
//@Date : 2024/03/25 15:26
|
||
//@Usage :
|
||
//@Desc :使用AST技术,还原code1.js
|
||
|
||
|
||
import {traverse, types} from "@babel/core";
|
||
import {parse} from "@babel/parser";
|
||
import CodeGenerator from "@babel/generator";
|
||
// import * as types from "@babel/types";
|
||
import fs from "fs";
|
||
|
||
//从系统盘读取文件 code4.js
|
||
|
||
const code = fs.readFileSync("code/code4.js", "utf-8");
|
||
let ast = parse(code)
|
||
|
||
traverse(ast, {
|
||
WhileStatement(path) {
|
||
const {node, scope} = path;
|
||
const {test, body} = node;
|
||
let switchNode = body.body[0];
|
||
let {discriminant, cases} = switchNode;
|
||
let {object, property} = discriminant;
|
||
|
||
let arrName = object.name;
|
||
let binding = scope.getBinding(arrName);
|
||
let {init} = binding.path.node;
|
||
object = init.callee.object;
|
||
property = init.callee.property;
|
||
let argument = init.arguments[0].value;
|
||
let arrayFlow = object.value[property.name](argument);
|
||
|
||
let resultBody = [];
|
||
arrayFlow.forEach((index) => {
|
||
let switchCase = cases.filter((c) => c.test.value == index)[0];
|
||
let caseBody = switchCase.consequent;
|
||
if (types.isContinueStatement(caseBody[caseBody.length - 1])) {
|
||
caseBody.pop();
|
||
}
|
||
resultBody = resultBody.concat(caseBody);
|
||
}
|
||
);
|
||
path.replaceWithMultiple(resultBody);
|
||
},
|
||
});
|
||
|
||
const {code: output} = CodeGenerator.default(ast);
|
||
console.log(output)
|
||
|
||
|
||
|
||
|
||
|