Last active
May 6, 2024 05:26
-
-
Save Becavalier/b7ae056a29043196f53dcece2f46b31a to your computer and use it in GitHub Desktop.
The basic usage of "UglifyJS.TreeTransformer".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const UglifyJS = require('uglify-js'); | |
var symbolTable = {}; | |
var binaryOperations = { | |
"+": (x, y) => x + y, | |
"-": (x, y) => x - y, | |
"*": (x, y) => x * y | |
} | |
var constexpr = new UglifyJS.TreeTransformer(null, function(node) { | |
if (node instanceof UglifyJS.AST_Binary) { | |
if (Number.isInteger(node.left.value) && Number.isInteger(node.right.value)) { | |
return new UglifyJS.AST_Number({ | |
value: binaryOperations[node.operator].call(this, | |
Number(node.left.value), | |
Number(node.right.value)) | |
}); | |
} else { | |
return new UglifyJS.AST_Number({ | |
value: binaryOperations[node.operator].call(this, | |
Number(symbolTable[node.left.name].value), | |
Number(symbolTable[node.right.name].value)) | |
}) | |
} | |
} | |
if (node instanceof UglifyJS.AST_VarDef) { | |
// AST_VarDef -> AST_SymbolVar; | |
symbolTable[node.name.name] = node.value; | |
} | |
}); | |
var ast = UglifyJS.parse(` | |
var x = 10 * 2 + 6; | |
var y = 4 - 1 * 100; | |
console.log(x + y); | |
`); | |
// transform and print | |
ast.transform(constexpr); | |
console.log(ast.print_to_string()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment