Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(transformer/react): correct import binding names #3014

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions crates/oxc_transformer/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use oxc_ast::AstBuilder;
use oxc_diagnostics::Error;
use oxc_semantic::Semantic;

use crate::{helpers::module_imports::ModuleImports, TransformOptions};
use crate::{helpers::module_imports::ModuleImports, naming::TransformerNaming, TransformOptions};

pub type Ctx<'a> = Rc<TransformCtx<'a>>;
Copy link
Member Author

Choose a reason for hiding this comment

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

TransformerNaming needs to mutation.

In a previous implementation. All the TransformerCtx fields that cannot be copied are wrapped in Rc

#[derive(Clone)]
pub struct TransformerCtx<'a> {
pub ast: Rc<AstBuilder<'a>>,
pub options: Cow<'a, TransformOptions>,
semantic: Rc<RefCell<Semantic<'a>>>,
errors: Rc<RefCell<Vec<Error>>>,
}

Copy link
Collaborator

Choose a reason for hiding this comment

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

This is a big change.

It probably makes more sense to use interior mutability in TransformerNaming, instead of adding all these borrow calls everywhere.

Copy link
Member Author

Choose a reason for hiding this comment

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

It probably makes more sense to use interior mutability in TransformerNaming, instead of adding all these borrow calls everywhere.

Yes, I agree. When we finally consider this PR, I'll refactor it.

pub type Ctx<'a> = Rc<RefCell<TransformCtx<'a>>>;

pub struct TransformCtx<'a> {
pub ast: AstBuilder<'a>,
Expand All @@ -30,6 +30,8 @@ pub struct TransformCtx<'a> {
// Helpers
/// Manage import statement globally
pub module_imports: ModuleImports<'a>,

pub naming: TransformerNaming<'a>,
}

impl<'a> TransformCtx<'a> {
Expand All @@ -54,6 +56,7 @@ impl<'a> TransformCtx<'a> {
source_path,
errors: RefCell::new(vec![]),
module_imports: ModuleImports::new(allocator),
naming: TransformerNaming::new(allocator),
}
}

Expand Down
10 changes: 7 additions & 3 deletions crates/oxc_transformer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod compiler_assumptions;
mod context;
mod options;
// Presets: <https://babel.dev/docs/presets>
mod naming;
mod react;
mod typescript;
mod utils;
Expand All @@ -20,12 +21,13 @@ mod helpers {
pub mod module_imports;
}

use std::{path::Path, rc::Rc};
use std::{cell::RefCell, path::Path, rc::Rc};

use oxc_allocator::{Allocator, Vec};
use oxc_ast::{
ast::*,
visit::{walk_mut, VisitMut},
Visit,
};
use oxc_diagnostics::Error;
use oxc_semantic::Semantic;
Expand Down Expand Up @@ -55,7 +57,8 @@ impl<'a> Transformer<'a> {
semantic: Semantic<'a>,
options: TransformOptions,
) -> Self {
let ctx = Rc::new(TransformCtx::new(allocator, source_path, semantic, &options));
let ctx =
Rc::new(RefCell::new(TransformCtx::new(allocator, source_path, semantic, &options)));
Self {
ctx: Rc::clone(&ctx),
x0_typescript: TypeScript::new(options.typescript, &ctx),
Expand All @@ -68,7 +71,7 @@ impl<'a> Transformer<'a> {
/// Returns `Vec<Error>` if any errors were collected during the transformation.
pub fn build(mut self, program: &mut Program<'a>) -> Result<(), std::vec::Vec<Error>> {
self.visit_program(program);
let errors = self.ctx.take_errors();
let errors = self.ctx.borrow().take_errors();
if errors.is_empty() {
Ok(())
} else {
Expand All @@ -79,6 +82,7 @@ impl<'a> Transformer<'a> {

impl<'a> VisitMut<'a> for Transformer<'a> {
fn visit_program(&mut self, program: &mut Program<'a>) {
self.ctx.borrow_mut().naming.visit_program(program);
Copy link
Member Author

Choose a reason for hiding this comment

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

We need to collect all bindings first.

walk_mut::walk_program_mut(self, program);
self.x1_react.transform_program_on_exit(program);
self.x0_typescript.transform_program_on_exit(program);
Expand Down
59 changes: 59 additions & 0 deletions crates/oxc_transformer/src/naming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use oxc_allocator::Allocator;
use oxc_ast::{
ast::{BindingIdentifier, LabeledStatement},
AstBuilder, Visit,
};
use oxc_span::{Atom, CompactStr};
use rustc_hash::FxHashSet;

pub struct TransformerNaming<'a> {
ast: AstBuilder<'a>,
bindings: FxHashSet<Atom<'a>>,
labels: FxHashSet<Atom<'a>>,
}

impl<'a> TransformerNaming<'a> {
pub fn new(allocator: &'a Allocator) -> Self {
let ast = AstBuilder::new(allocator);
Self { ast, bindings: FxHashSet::default(), labels: FxHashSet::default() }
}

pub fn has_binding(&self, name: &str) -> bool {
self.bindings.contains(name)
}

pub fn has_label(&self, name: &str) -> bool {
self.labels.contains(name)
}

// <https://github.com/babel/babel/blob/419644f27c5c59deb19e71aaabd417a3bc5483ca/packages/babel-traverse/src/scope/index.ts#L495>
pub fn generate_uid(&mut self, name: &str) -> CompactStr {
for i in 0.. {
let name = Self::internal_generate_uid(name, i);
if self.has_binding(&name) || self.has_label(&name) {
continue;
}

// Add the generated name to the bindings set.
self.bindings.insert(self.ast.new_atom(name.as_str()));

return name;
}
unreachable!()
}

// <https://github.com/babel/babel/blob/419644f27c5c59deb19e71aaabd417a3bc5483ca/packages/babel-traverse/src/scope/index.ts#L523>
fn internal_generate_uid(name: &str, i: i32) -> CompactStr {
CompactStr::from(if i > 1 { format!("_{name}{i}") } else { format!("_{name}") })
}
}

impl<'a> Visit<'a> for TransformerNaming<'a> {
fn visit_binding_identifier(&mut self, ident: &BindingIdentifier<'a>) {
self.bindings.insert(ident.name.clone());
}

fn visit_labeled_statement(&mut self, stmt: &LabeledStatement<'a>) {
self.labels.insert(stmt.label.name.clone());
}
}
15 changes: 8 additions & 7 deletions crates/oxc_transformer/src/react/display_name/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl<'a> ReactDisplayName<'a> {
SimpleAssignmentTarget::MemberAssignmentTarget(target),
) => {
if let Some(name) = target.static_property_name() {
self.ctx.ast.new_atom(name)
self.ctx.borrow().ast.new_atom(name)
} else {
return;
}
Expand All @@ -70,7 +70,7 @@ impl<'a> ReactDisplayName<'a> {
pub fn transform_object_property(&self, prop: &mut ObjectProperty<'a>) {
let Some(obj_expr) = Self::get_object_from_create_class(&mut prop.value) else { return };
let Some(name) = prop.key.static_name() else { return };
let name = self.ctx.ast.new_atom(&name);
let name = self.ctx.borrow().ast.new_atom(&name);
self.add_display_name(obj_expr, name);
}

Expand All @@ -79,7 +79,7 @@ impl<'a> ReactDisplayName<'a> {
pub fn transform_export_default_declaration(&self, decl: &mut ExportDefaultDeclaration<'a>) {
let ExportDefaultDeclarationKind::Expression(expr) = &mut decl.declaration else { return };
let Some(obj_expr) = Self::get_object_from_create_class(expr) else { return };
let name = self.ctx.ast.new_atom(self.ctx.filename());
let name = self.ctx.borrow().ast.new_atom(self.ctx.borrow().filename());
self.add_display_name(obj_expr, name);
}
}
Expand Down Expand Up @@ -123,11 +123,12 @@ impl<'a> ReactDisplayName<'a> {
}
let object_property = {
let kind = PropertyKind::Init;
let identifier_name = IdentifierName::new(SPAN, self.ctx.ast.new_atom(DISPLAY_NAME));
let key = self.ctx.ast.property_key_identifier(identifier_name);
let identifier_name =
IdentifierName::new(SPAN, self.ctx.borrow().ast.new_atom(DISPLAY_NAME));
let key = self.ctx.borrow().ast.property_key_identifier(identifier_name);
let string_literal = StringLiteral::new(SPAN, name);
let value = self.ctx.ast.literal_string_expression(string_literal);
self.ctx.ast.object_property(SPAN, kind, key, value, None, false, false, false)
let value = self.ctx.borrow().ast.literal_string_expression(string_literal);
self.ctx.borrow().ast.object_property(SPAN, kind, key, value, None, false, false, false)
};
obj_expr.properties.insert(0, ObjectPropertyKind::ObjectProperty(object_property));
}
Expand Down