How to replace a Identifier node with a Literal node? #8065
-
I'm building a constant folding optimization pass. This is a contrived example of what I'm trying to achieve. This is the orignal JS code. const PI = 3.14;
function getPI() {
return PI;
}
function area(r) {
return PI * r * r;
} I want to simplify it to the below. function getPI() {
return 3.14;
}
function area(r) {
return 3.14 * r * r;
} Using Scope and Bindings can already find out the places the variable For example, Is there a way to avoid implemeting |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
use oxc_ast::{
ast::{Expression, NumberBase},
visit::VisitMut,
AstBuilder,
};
struct PiReplacer<'a> {
ast_builder: AstBuilder<'a>,
}
impl<'a> VisitMut<'a> for PiReplacer<'a> {
fn visit_expression(&mut self, expr: &mut Expression<'a>) {
if let Expression::Identifier(ident) = expr {
if ident.name == "PI" {
*expr = self.ast_builder.expression_numeric_literal(
ident.span,
3.14,
None,
NumberBase::Decimal,
);
}
}
}
} |
Beta Was this translation helpful? Give feedback.
PI
is anIdentifierReference
, which is a variant ofExpression
enum. So you can useVisitMut::visit_expression
and replace thatExpression
with a different kind ofExpression
.