Skip to content

Commit

Permalink
refactor: use trait instead of enum for SourceMutation (#25)
Browse files Browse the repository at this point in the history
* refactor: use `trait` instead of `enum` for `SourceMutation`

* Remobe all old impl and add new impl
  • Loading branch information
hyf0 authored Oct 6, 2023
1 parent 68ca330 commit 222c5a3
Show file tree
Hide file tree
Showing 14 changed files with 150 additions and 80 deletions.
1 change: 1 addition & 0 deletions crates/rolldown/src/bundler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub mod bundle;
mod graph;
mod module;
pub mod options;
pub mod source_mutations;
mod visitors;

#[allow(clippy::module_inception)]
Expand Down
1 change: 0 additions & 1 deletion crates/rolldown/src/bundler/module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ pub mod module_builder;
pub mod module_id;
pub mod normal_module;
pub mod render;
pub mod source_mutation;
pub use normal_module::NormalModule;
2 changes: 1 addition & 1 deletion crates/rolldown/src/bundler/module/module_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl ModuleBuilder {
default_export_symbol: self.default_export_symbol,
namespace_symbol: self.namespace_symbol.unwrap(),
is_symbol_for_namespace_referenced: false,
source_mutations: vec![],
source_mutations: Default::default(),
}
}
}
24 changes: 19 additions & 5 deletions crates/rolldown/src/bundler/module/normal_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ use rolldown_common::{
use rolldown_oxc::OxcProgram;
use rustc_hash::{FxHashMap, FxHashSet};

use super::{module::ModuleFinalizeContext, module_id::ModuleVec, source_mutation::SourceMutation};
use super::{module::ModuleFinalizeContext, module_id::ModuleVec};
use crate::bundler::{
graph::symbols::Symbols,
module::module::Module,
source_mutations::{append::Append, BoxedSourceMutation},
visitors::{FinalizeContext, Finalizer},
};

Expand All @@ -26,7 +27,7 @@ pub struct NormalModule {
pub id: ModuleId,
pub resource_id: ResourceId,
pub ast: OxcProgram,
pub source_mutations: Vec<SourceMutation>,
pub source_mutations: Vec<BoxedSourceMutation>,
pub named_imports: FxHashMap<SymbolId, NamedImport>,
pub named_exports: FxHashMap<Atom, LocalOrReExport>,
pub stmt_infos: IndexVec<StmtInfoId, StmtInfo>,
Expand Down Expand Up @@ -56,12 +57,25 @@ impl NormalModule {
id: self.id,
final_names: ctx.canonical_names,
source_mutations: &mut self.source_mutations,
default_export_symbol: self.default_export_symbol.map(|id| (self.id, id).into()),
});
finalizer.visit_program(program);
if self.is_symbol_for_namespace_referenced {
self
.source_mutations
.push(SourceMutation::AddNamespaceExport());
let ns_ref = ctx.symbols.par_get_canonical_ref(self.namespace_symbol.0);
let ns_name = ctx.canonical_names.get(&ns_ref).unwrap();
let exports: String = self
.resolved_exports
.iter()
.map(|(exported_name, info)| {
let canonical_ref = ctx.symbols.par_get_canonical_ref(info.local_symbol);
let canonical_name = ctx.canonical_names.get(&canonical_ref).unwrap();
format!(" get {exported_name}() {{ return {canonical_name} }}",)
})
.collect::<Vec<_>>()
.join(",\n");
self.source_mutations.push(Box::new(Append {
content: format!("\nvar {ns_name} = {{\n{exports}\n}};\n"),
}));
}
}

Expand Down
60 changes: 8 additions & 52 deletions crates/rolldown/src/bundler/module/render.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::{source_mutation::SourceMutation, NormalModule};
use super::NormalModule;
use crate::bundler::{
graph::symbols::{get_reference_final_name, get_symbol_final_name, Symbols},
options::normalized_input_options::NormalizedInputOptions,
graph::symbols::Symbols, options::normalized_input_options::NormalizedInputOptions,
source_mutations,
};
use oxc::span::Atom;
use rolldown_common::SymbolRef;
Expand All @@ -16,58 +16,14 @@ pub struct RenderModuleContext<'a> {
}

impl NormalModule {
pub fn render(&self, ctx: RenderModuleContext<'_>) -> Option<MagicString<'_>> {
pub fn render(&self, _ctx: RenderModuleContext<'_>) -> Option<MagicString<'_>> {
let mut s = MagicString::new(self.ast.source());

s.prepend(format!("// {}\n", self.resource_id.prettify()));
self.source_mutations.iter().for_each(|mutation| {
mutation.apply(&source_mutations::Context {}, &mut s);
});

for mutation in &self.source_mutations {
match mutation {
SourceMutation::RenameSymbol(r) => {
s.update(r.0.start, r.0.end, r.1.as_str());
}
SourceMutation::Remove(span) => {
s.remove(span.start, span.end);
}
SourceMutation::AddExportDefaultBindingIdentifier(span) => {
if let Some(name) = get_symbol_final_name(
self.id,
self.default_export_symbol.unwrap(),
ctx.symbols,
ctx.final_names,
) {
s.update(span.start, span.end, format!("var {name} = "));
}
}
SourceMutation::AddNamespaceExport() => {
if let Some(name) = get_symbol_final_name(
self.id,
self.namespace_symbol.0.symbol,
ctx.symbols,
ctx.final_names,
) {
let exports = self
.resolved_exports
.iter()
.map(|(name, info)| {
format!(
" get {name}() {{ return {} }}",
if let Some(name) =
get_reference_final_name(self.id, info.local_ref, ctx.symbols, ctx.final_names,)
{
name
} else {
name
}
)
})
.collect::<Vec<_>>()
.join(",\n");
s.append(format!("\nvar {name} = {{\n{exports}\n}};\n"));
}
}
}
}
s.prepend(format!("// {}\n", self.resource_id.prettify()));

// TODO trim
if s.len() == 0 {
Expand Down
9 changes: 0 additions & 9 deletions crates/rolldown/src/bundler/module/source_mutation.rs

This file was deleted.

12 changes: 12 additions & 0 deletions crates/rolldown/src/bundler/source_mutations/append.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use super::SourceMutation;

#[derive(Debug)]
pub struct Append {
pub content: String,
}

impl SourceMutation for Append {
fn apply<'me>(&'me self, _ctx: &super::Context, s: &mut string_wizard::MagicString<'me>) {
s.append(&self.content);
}
}
18 changes: 18 additions & 0 deletions crates/rolldown/src/bundler/source_mutations/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod append;
pub mod overwrite;
pub mod remove_range;
pub mod rename_symbol;

use std::fmt::Debug;

use string_wizard::MagicString;

#[derive(Debug)]
pub struct Context {}

pub trait SourceMutation: Debug + Sync + Send {
#[allow(unused_variables)]
fn apply<'me>(&'me self, ctx: &Context, s: &mut MagicString<'me>) {}
}

pub type BoxedSourceMutation = Box<dyn SourceMutation>;
24 changes: 24 additions & 0 deletions crates/rolldown/src/bundler/source_mutations/overwrite.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use oxc::span::Span;
use string_wizard::UpdateOptions;

use super::SourceMutation;

#[derive(Debug)]
pub struct Overwrite {
pub span: Span,
pub content: String,
}

impl SourceMutation for Overwrite {
fn apply<'me>(&'me self, _ctx: &super::Context, s: &mut string_wizard::MagicString<'me>) {
s.update_with(
self.span.start,
self.span.end,
&self.content,
UpdateOptions {
overwrite: true,
..Default::default()
},
);
}
}
13 changes: 13 additions & 0 deletions crates/rolldown/src/bundler/source_mutations/remove_node.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use oxc::span::Span;

use super::SourceMutation;

pub struct RemoveNode {
pub span: Span,
}

impl SourceMutation for RemoveNode {
fn apply<'me>(&'me self, _ctx: &super::Context, s: &mut string_wizard::MagicString<'me>) {
s.remove(self.span.start, self.span.end);
}
}
14 changes: 14 additions & 0 deletions crates/rolldown/src/bundler/source_mutations/remove_range.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use oxc::span::Span;

use super::SourceMutation;

#[derive(Debug)]
pub struct RemoveRange {
pub span: Span,
}

impl SourceMutation for RemoveRange {
fn apply<'me>(&'me self, _ctx: &super::Context, s: &mut string_wizard::MagicString<'me>) {
s.remove(self.span.start, self.span.end);
}
}
15 changes: 15 additions & 0 deletions crates/rolldown/src/bundler/source_mutations/rename_symbol.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use oxc::span::{Atom, Span};

use super::SourceMutation;

#[derive(Debug)]
pub struct RenameSymbol {
pub span: Span,
pub name: Atom,
}

impl SourceMutation for RenameSymbol {
fn apply<'me>(&'me self, _ctx: &super::Context, s: &mut string_wizard::MagicString<'me>) {
s.update(self.span.start, self.span.end, self.name.as_str());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use oxc::span::Span;

//
pub struct RewriteDefaultExport {
pub span: Span,
}
31 changes: 19 additions & 12 deletions crates/rolldown/src/bundler/visitors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,18 @@ use rustc_hash::FxHashMap;

use super::{
graph::symbols::{get_reference_final_name, get_symbol_final_name, Symbols},
module::source_mutation::SourceMutation,
source_mutations::{
overwrite::Overwrite, remove_range::RemoveRange, rename_symbol::RenameSymbol,
BoxedSourceMutation,
},
};

pub struct FinalizeContext<'ast> {
pub symbols: &'ast Symbols,
pub final_names: &'ast FxHashMap<SymbolRef, Atom>,
pub id: ModuleId,
pub source_mutations: &'ast mut Vec<SourceMutation>,
pub source_mutations: &'ast mut Vec<BoxedSourceMutation>,
pub default_export_symbol: Option<SymbolRef>,
}

pub struct Finalizer<'ast> {
Expand All @@ -32,14 +36,14 @@ impl<'ast> Finalizer<'ast> {
self
.ctx
.source_mutations
.push(SourceMutation::Remove(Box::new(span)));
.push(Box::new(RemoveRange { span }))
}

pub fn remove_symbol(&mut self, span: Span, name: Atom) {
pub fn rename_symbol(&mut self, span: Span, name: Atom) {
self
.ctx
.source_mutations
.push(SourceMutation::RenameSymbol(Box::new((span, name))));
.push(Box::new(RenameSymbol { span, name }))
}
}

Expand All @@ -52,7 +56,7 @@ impl<'ast, 'p> VisitMut<'ast, 'p> for Finalizer<'ast> {
self.ctx.final_names,
) {
if ident.name != name {
self.remove_symbol(ident.span, name.clone());
self.rename_symbol(ident.span, name.clone());
}
}
}
Expand All @@ -65,7 +69,7 @@ impl<'ast, 'p> VisitMut<'ast, 'p> for Finalizer<'ast> {
self.ctx.final_names,
) {
if ident.name != name {
self.remove_symbol(ident.span, name.clone());
self.rename_symbol(ident.span, name.clone());
}
}
}
Expand Down Expand Up @@ -99,12 +103,15 @@ impl<'ast, 'p> VisitMut<'ast, 'p> for Finalizer<'ast> {
) {
match &decl.declaration {
oxc::ast::ast::ExportDefaultDeclarationKind::Expression(exp) => {
self
let canonical_ref = self
.ctx
.source_mutations
.push(SourceMutation::AddExportDefaultBindingIdentifier(Box::new(
Span::new(decl.span.start, exp.span().start),
)));
.symbols
.par_get_canonical_ref(self.ctx.default_export_symbol.unwrap());
let canonical_name = self.ctx.final_names.get(&canonical_ref).unwrap().clone();
self.ctx.source_mutations.push(Box::new(Overwrite {
span: Span::new(decl.span.start, exp.span().start),
content: format!("var {canonical_name} = "),
}));
}
oxc::ast::ast::ExportDefaultDeclarationKind::FunctionDeclaration(decl) => {
self.remove_node(Span::new(decl.span.start, decl.span.start));
Expand Down

0 comments on commit 222c5a3

Please sign in to comment.