Skip to content

Commit

Permalink
Merge branch 'main' into dce-par
Browse files Browse the repository at this point in the history
  • Loading branch information
kdy1 authored Jan 15, 2025
2 parents 313dc2f + 197f0bc commit 57ff7b8
Show file tree
Hide file tree
Showing 6 changed files with 172 additions and 76 deletions.
5 changes: 5 additions & 0 deletions .changeset/curly-poems-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
swc_fast_ts_strip: minor
---

fix(es/ts_strip): Handle ASI hazard in return statement
138 changes: 71 additions & 67 deletions crates/swc_ecma_minifier/examples/minify-all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{env, fs, path::PathBuf, time::Instant};

use anyhow::Result;
use rayon::prelude::*;
use swc_common::{errors::HANDLER, sync::Lrc, Mark, SourceMap, GLOBALS};
use swc_common::{sync::Lrc, Mark, SourceMap, GLOBALS};
use swc_ecma_ast::Program;
use swc_ecma_codegen::text_writer::JsWriter;
use swc_ecma_minifier::{
Expand All @@ -18,6 +18,7 @@ use swc_ecma_transforms_base::{
fixer::{fixer, paren_remover},
resolver,
};
use swc_ecma_utils::parallel::{Parallel, ParallelExt};
use walkdir::WalkDir;

fn main() {
Expand All @@ -26,72 +27,7 @@ fn main() {
eprintln!("Using {} files", files.len());

let start = Instant::now();
testing::run_test2(false, |cm, handler| {
GLOBALS.with(|globals| {
HANDLER.set(&handler, || {
let _ = files
.into_iter()
.map(|path| -> Result<_> {
GLOBALS.set(globals, || {
let fm = cm.load_file(&path).expect("failed to load file");

let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

let program = parse_file_as_module(
&fm,
Default::default(),
Default::default(),
None,
&mut Vec::new(),
)
.map_err(|err| {
err.into_diagnostic(&handler).emit();
})
.map(Program::Module)
.map(|module| {
module.apply(&mut resolver(unresolved_mark, top_level_mark, false))
})
.map(|module| module.apply(&mut paren_remover(None)))
.unwrap();

let output = optimize(
program,
cm.clone(),
None,
None,
&MinifyOptions {
compress: Some(Default::default()),
mangle: Some(MangleOptions {
top_level: Some(true),
..Default::default()
}),
..Default::default()
},
&ExtraOptions {
unresolved_mark,
top_level_mark,
mangle_name_cache: None,
},
);

let output = output.apply(&mut fixer(None));

let code = print(cm.clone(), &[output], true);

fs::write("output.js", code.as_bytes())
.expect("failed to write output");

Ok(())
})
})
.collect::<Vec<_>>();

Ok(())
})
})
})
.unwrap();
minify_all(files);

eprintln!("Took {:?}", start.elapsed());
}
Expand All @@ -118,6 +54,74 @@ fn expand_dirs(dirs: Vec<String>) -> Vec<PathBuf> {
.collect()
}

struct Worker;

impl Parallel for Worker {
fn create(&self) -> Self {
Worker
}

fn merge(&mut self, _: Self) {}
}

#[inline(never)] // For profiling
fn minify_all(files: Vec<PathBuf>) {
GLOBALS.set(&Default::default(), || {
Worker.maybe_par(2, files, |_, path| {
testing::run_test(false, |cm, handler| {
let fm = cm.load_file(&path).expect("failed to load file");

let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

let program = parse_file_as_module(
&fm,
Default::default(),
Default::default(),
None,
&mut Vec::new(),
)
.map_err(|err| {
err.into_diagnostic(handler).emit();
})
.map(Program::Module)
.map(|module| module.apply(&mut resolver(unresolved_mark, top_level_mark, false)))
.map(|module| module.apply(&mut paren_remover(None)))
.unwrap();

let output = optimize(
program,
cm.clone(),
None,
None,
&MinifyOptions {
compress: Some(Default::default()),
mangle: Some(MangleOptions {
top_level: Some(true),
..Default::default()
}),
..Default::default()
},
&ExtraOptions {
unresolved_mark,
top_level_mark,
mangle_name_cache: None,
},
);

let output = output.apply(&mut fixer(None));

let code = print(cm.clone(), &[output], true);

fs::write("output.js", code.as_bytes()).expect("failed to write output");

Ok(())
})
.unwrap()
});
});
}

fn print<N: swc_ecma_codegen::Node>(cm: Lrc<SourceMap>, nodes: &[N], minify: bool) -> String {
let mut buf = Vec::new();

Expand Down
60 changes: 51 additions & 9 deletions crates/swc_fast_ts_strip/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ use swc_ecma_ast::{
Constructor, Decl, DefaultDecl, DoWhileStmt, EsVersion, ExportAll, ExportDecl,
ExportDefaultDecl, ExportSpecifier, FnDecl, ForInStmt, ForOfStmt, ForStmt, GetterProp, IfStmt,
ImportDecl, ImportSpecifier, NamedExport, ObjectPat, Param, Pat, PrivateMethod, PrivateProp,
Program, SetterProp, Stmt, TsAsExpr, TsConstAssertion, TsEnumDecl, TsExportAssignment,
TsImportEqualsDecl, TsIndexSignature, TsInstantiation, TsModuleDecl, TsModuleName,
TsNamespaceDecl, TsNonNullExpr, TsParamPropParam, TsSatisfiesExpr, TsTypeAliasDecl, TsTypeAnn,
TsTypeAssertion, TsTypeParamDecl, TsTypeParamInstantiation, VarDeclarator, WhileStmt,
Program, ReturnStmt, SetterProp, Stmt, TsAsExpr, TsConstAssertion, TsEnumDecl,
TsExportAssignment, TsImportEqualsDecl, TsIndexSignature, TsInstantiation, TsModuleDecl,
TsModuleName, TsNamespaceDecl, TsNonNullExpr, TsParamPropParam, TsSatisfiesExpr,
TsTypeAliasDecl, TsTypeAnn, TsTypeAssertion, TsTypeParamDecl, TsTypeParamInstantiation,
VarDeclarator, WhileStmt,
};
use swc_ecma_parser::{
lexer::Lexer,
Expand Down Expand Up @@ -610,11 +611,6 @@ impl Visit for TsStrip {
}

fn visit_arrow_expr(&mut self, n: &ArrowExpr) {
#[inline(always)]
fn is_new_line(c: char) -> bool {
matches!(c, '\u{000A}' | '\u{000D}' | '\u{2028}' | '\u{2029}')
}

'type_params: {
// ```TypeScript
// let f = async <
Expand Down Expand Up @@ -692,6 +688,48 @@ impl Visit for TsStrip {
n.body.visit_with(self);
}

fn visit_return_stmt(&mut self, n: &ReturnStmt) {
let Some(arg) = n.arg.as_deref() else {
return;
};

arg.visit_with(self);

if let Some(arrow_expr) = arg.as_arrow() {
if arrow_expr.is_async {
// We have already handled type parameters in `visit_arrow_expr`.
return;
}

// ```TypeScript
// return <T>
// (v: T) => v;
// ```
//
// ```TypeScript
// return (
// v ) => v;
// ```

if let Some(tp) = &arrow_expr.type_params {
let l_paren = self.get_next_token(tp.span.hi);
debug_assert_eq!(l_paren.token, Token::LParen);

let slice = self.get_src_slice(tp.span.with_hi(l_paren.span.lo));

if !slice.chars().any(is_new_line) {
return;
}

let l_paren_pos = l_paren.span.lo;
let l_lt_pos = tp.span.lo;

self.add_overwrite(l_paren_pos, b' ');
self.add_overwrite(l_lt_pos, b'(');
}
}
}

fn visit_binding_ident(&mut self, n: &BindingIdent) {
n.visit_children_with(self);

Expand Down Expand Up @@ -1303,6 +1341,10 @@ impl Visit for TsStrip {
}
}

#[inline(always)]
fn is_new_line(c: char) -> bool {
matches!(c, '\u{000A}' | '\u{000D}' | '\u{2028}' | '\u{2029}')
}
trait IsTsDecl {
fn is_ts_declare(&self) -> bool;
}
Expand Down
18 changes: 18 additions & 0 deletions crates/swc_fast_ts_strip/tests/fixture/issue-9878.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function f() {
return (
x )=>x;
}

function f2() {
return (

x )=>x;
}


function f3() {
return (

x
)=>x;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function f() {
return (x)=>x;
}
function f2() {
return (x)=>x;
}
function f3() {
return (x)=>x;
}
18 changes: 18 additions & 0 deletions crates/swc_fast_ts_strip/tests/fixture/issue-9878.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function f() {
return <T>
(x: T)=>x;
}

function f2() {
return <T
>
(x: T)=>x;
}


function f3() {
return <T
>
(x: T): Promise<
T>=>x;
}

0 comments on commit 57ff7b8

Please sign in to comment.