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/commonjs): support deconflict exports key. #5786

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions crates/oxc_transformer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ mod es2018;
mod es2019;
mod es2020;
mod es2021;
mod modules;
mod react;
mod regexp;
mod typescript;
Expand Down Expand Up @@ -55,6 +56,7 @@ pub use crate::{
use crate::{
context::{Ctx, TransformCtx},
es2015::ES2015,
modules::Modules,
react::React,
typescript::TypeScript,
};
Expand All @@ -70,6 +72,7 @@ pub struct Transformer<'a> {
// NOTE: all callbacks must run in order.
x0_typescript: TypeScript<'a>,
x1_react: React<'a>,
x1_modules: Modules<'a>,
x2_es2021: ES2021<'a>,
x2_es2020: ES2020<'a>,
x2_es2019: ES2019<'a>,
Expand Down Expand Up @@ -100,6 +103,7 @@ impl<'a> Transformer<'a> {
ctx: Rc::clone(&ctx),
x0_typescript: TypeScript::new(options.typescript, Rc::clone(&ctx)),
x1_react: React::new(options.react, Rc::clone(&ctx)),
x1_modules: Modules::new(options.modules, Rc::clone(&ctx)),
x2_es2021: ES2021::new(options.es2021, Rc::clone(&ctx)),
x2_es2020: ES2020::new(options.es2020, Rc::clone(&ctx)),
x2_es2019: ES2019::new(options.es2019, Rc::clone(&ctx)),
Expand Down Expand Up @@ -421,4 +425,24 @@ impl<'a> Traverse<'a> for Transformer<'a> {
) {
self.x0_typescript.enter_ts_export_assignment(export_assignment, ctx);
}

fn exit_identifier_name(&mut self, node: &mut IdentifierName<'a>, ctx: &mut TraverseCtx<'a>) {
self.x1_modules.exit_identifier_name(node, ctx);
}

fn exit_identifier_reference(
&mut self,
node: &mut IdentifierReference<'a>,
ctx: &mut TraverseCtx<'a>,
) {
self.x1_modules.exit_identifier_reference(node, ctx);
}

fn enter_binding_identifier(
&mut self,
node: &mut BindingIdentifier<'a>,
ctx: &mut TraverseCtx<'a>,
) {
self.x1_modules.enter_binding_identifier(node, ctx);
}
}
78 changes: 78 additions & 0 deletions crates/oxc_transformer/src/modules/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use crate::context::Ctx;
use crate::modules::options::{format::ModulesFormat, ModulesOptions};
use oxc_ast::ast::{BindingIdentifier, IdentifierName, IdentifierReference};
use oxc_traverse::{Traverse, TraverseCtx};

pub mod options;

pub struct Modules<'a> {
ctx: Ctx<'a>,
options: ModulesOptions,

/// Because the `exports` is the keyword ONLY when the format is `Commonjs`, `let exports = {}` is valid in ES6.
/// But if we want to transform the code to CommonJS, we need to rename the `exports` to `_exports`, or other deconflicted names.
rename_exports_to: String,
}

impl<'a> Modules<'a> {
pub fn new(options: ModulesOptions, ctx: Ctx<'a>) -> Self {
Self { ctx, options, rename_exports_to: "_exports".to_string() }
}
}

impl<'a> Traverse<'a> for Modules<'a> {
fn exit_identifier_name(&mut self, ident: &mut IdentifierName<'a>, _ctx: &mut TraverseCtx<'a>) {
// deconflict exports
if ident.name.as_str() == "exports"
&& matches!(self.options.format, ModulesFormat::Commonjs)
{
ident.name = self.ctx.ast.atom(self.rename_exports_to.as_str());
}
}

fn exit_identifier_reference(
&mut self,
reference: &mut IdentifierReference<'a>,
ctx: &mut TraverseCtx<'a>,
) {
if reference.name.as_str() == "exports"
&& matches!(self.options.format, ModulesFormat::Commonjs)
{
reference.name = ctx.ast.atom(self.rename_exports_to.as_str());
}
}

fn enter_binding_identifier(
&mut self,
ident: &mut BindingIdentifier<'a>,
ctx: &mut TraverseCtx<'a>,
) {
if ident.name.as_str() == "exports"
&& matches!(self.options.format, ModulesFormat::Commonjs)
{
let symbol_id = ident.symbol_id.get();
if let Some(symbol) = symbol_id {
let symbols = ctx.symbols_mut();
let names = &symbols.names.raw;
// 1. Check if `_exports` is available.
// 2. Check if `_exports{i}` is available (i = 1, 2, 3, ...).
// 3. If not, create a new symbol, and save to `self.rename_exports_to`.
let target_name = if names.iter().any(|name| name == "_exports") {
let mut i = 1;
let mut dest = format!("_exports{i}");
while names.iter().any(|name| name == &dest) {
i += 1;
dest = format!("_exports{i}");
}
dest
} else {
"_exports".to_string()
};
symbols.set_name(symbol, target_name.as_str().into());
ident.name = ctx.ast.atom(target_name.as_str());
self.rename_exports_to = target_name;
// Find out if there's `_exports`, `_exports1`, etc.
}
}
}
}
15 changes: 15 additions & 0 deletions crates/oxc_transformer/src/modules/options/format.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#[derive(Debug, Default, Clone)]
pub enum ModulesFormat {
#[default]
None,
Commonjs,
}

impl From<&str> for ModulesFormat {
fn from(s: &str) -> Self {
match s {
"commonjs" => Self::Commonjs,
_ => Self::None,
}
}
}
14 changes: 14 additions & 0 deletions crates/oxc_transformer/src/modules/options/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
pub mod format;

use format::ModulesFormat;

#[derive(Debug, Default, Clone)]
pub struct ModulesOptions {
pub format: ModulesFormat,
}

impl ModulesOptions {
pub fn new(format: ModulesFormat) -> Self {
Self { format }
}
}
4 changes: 4 additions & 0 deletions crates/oxc_transformer/src/options/transformer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::path::PathBuf;
use oxc_diagnostics::{Error, OxcDiagnostic};
use serde_json::{from_value, json, Value};

use crate::modules::options::ModulesOptions;
use crate::{
compiler_assumptions::CompilerAssumptions,
env::{can_enable_plugin, EnvOptions, Versions},
Expand Down Expand Up @@ -53,6 +54,8 @@ pub struct TransformOptions {
pub es2020: ES2020Options,

pub es2021: ES2021Options,

pub modules: ModulesOptions,
}

impl TransformOptions {
Expand Down Expand Up @@ -86,6 +89,7 @@ impl TransformOptions {
es2019: ES2019Options { optional_catch_binding: true },
es2020: ES2020Options { nullish_coalescing_operator: true },
es2021: ES2021Options { logical_assignment_operators: true },
modules: ModulesOptions::default(),
}
}

Expand Down