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

perf(es): Don't share Globals #5975

Merged
merged 15 commits into from
Sep 28, 2022
Merged
Show file tree
Hide file tree
Changes from 9 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
10 changes: 6 additions & 4 deletions crates/swc/benches/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use std::{

use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
use swc::config::{Config, IsModule, JscConfig, Options, SourceMapsConfig};
use swc_common::{errors::Handler, FileName, FilePathMapping, Mark, SourceFile, SourceMap};
use swc_common::{
errors::Handler, FileName, FilePathMapping, Mark, SourceFile, SourceMap, GLOBALS,
};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_parser::{Syntax, TsConfig};
use swc_ecma_transforms::{fixer, hygiene, resolver, typescript};
Expand Down Expand Up @@ -63,7 +65,7 @@ fn base_tr_group(c: &mut Criterion) {

fn base_tr_fixer(b: &mut Bencher) {
let c = mk();
c.run(|| {
GLOBALS.set(&Default::default(), || {
let module = as_es(&c);

b.iter(|| {
Expand All @@ -77,7 +79,7 @@ fn base_tr_fixer(b: &mut Bencher) {

fn base_tr_resolver_and_hygiene(b: &mut Bencher) {
let c = mk();
c.run(|| {
GLOBALS.set(&Default::default(), || {
let module = as_es(&c);

b.iter(|| {
Expand All @@ -97,7 +99,7 @@ fn base_tr_resolver_and_hygiene(b: &mut Bencher) {
fn bench_codegen(b: &mut Bencher, _target: EsVersion) {
let c = mk();

c.run(|| {
GLOBALS.set(&Default::default(), || {
let module = as_es(&c);

//TODO: Use target
Expand Down
18 changes: 7 additions & 11 deletions crates/swc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ use swc_common::{
errors::Handler,
source_map::SourceMapGenConfig,
sync::Lrc,
BytePos, FileName, Globals, Mark, SourceFile, SourceMap, Spanned, GLOBALS,
BytePos, FileName, Mark, SourceFile, SourceMap, Spanned, GLOBALS,
};
pub use swc_config::config_types::{BoolConfig, BoolOr, BoolOrDataConfig};
use swc_config::merge::Merge;
Expand Down Expand Up @@ -216,10 +216,6 @@ type SwcImportResolver =
/// The caller should check if the handler contains any errors after calling
/// method.
pub struct Compiler {
/// swc uses rustc's span interning.
///
/// The `Globals` struct contains span interner.
globals: Globals,
/// CodeMap
pub cm: Arc<SourceMap>,
comments: SwcComments,
Expand All @@ -244,10 +240,6 @@ pub struct TransformOutput {

/// These are **low-level** apis.
impl Compiler {
pub fn globals(&self) -> &Globals {
&self.globals
}

pub fn comments(&self) -> &SwcComments {
&self.comments
}
Expand All @@ -259,7 +251,12 @@ impl Compiler {
where
F: FnOnce() -> R,
{
GLOBALS.set(&self.globals, op)
debug_assert!(
GLOBALS.is_set(),
"`swc_common::GLOBALS` is required for this operation"
);

op()
}

fn get_orig_src_map(
Expand Down Expand Up @@ -646,7 +643,6 @@ impl Compiler {
pub fn new(cm: Arc<SourceMap>) -> Self {
Compiler {
cm,
globals: Globals::new(),
comments: Default::default(),
}
}
Expand Down
58 changes: 30 additions & 28 deletions crates/swc/tests/error_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use swc::{
config::{Config, IsModule, Options},
try_with_handler, Compiler, HandlerOpts,
};
use swc_common::{errors::ColorConfig, sync::Lrc, FilePathMapping, SourceMap};
use swc_common::{errors::ColorConfig, sync::Lrc, FilePathMapping, SourceMap, GLOBALS};
use testing::{NormalizedOutput, Tester};

fn file(f: impl AsRef<Path>) -> NormalizedOutput {
Expand Down Expand Up @@ -55,38 +55,40 @@ fn fixture(input: PathBuf) {
let output_path = input.parent().unwrap().join("output.swc-stderr");

let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let err = try_with_handler(
cm.clone(),
HandlerOpts {
skip_filename: true,
color: ColorConfig::Never,
},
|handler| {
let c = Compiler::new(cm.clone());
let err = GLOBALS.set(&Default::default(), || {
try_with_handler(
cm.clone(),
HandlerOpts {
skip_filename: true,
color: ColorConfig::Never,
},
|handler| {
let c = Compiler::new(cm.clone());

let fm = cm.load_file(&input).expect("failed to load file");
let fm = cm.load_file(&input).expect("failed to load file");

match c.process_js_file(
fm,
handler,
&Options {
config: Config {
is_module: IsModule::Unknown,
..Default::default()
},
swcrc: true,

match c.process_js_file(
fm,
handler,
&Options {
config: Config {
is_module: IsModule::Unknown,
..Default::default()
},
swcrc: true,

..Default::default()
},
) {
Ok(..) => {}
Err(err) => return Err(err),
}
) {
Ok(..) => {}
Err(err) => return Err(err),
}

Ok(())
},
)
.expect_err("should fail");
Ok(())
},
)
.expect_err("should fail")
});

let output = NormalizedOutput::from(format!("{}", err));

Expand Down
192 changes: 98 additions & 94 deletions crates/swc/tests/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use swc::{
config::{Config, JsMinifyOptions, JscConfig, ModuleConfig, Options, SourceMapsConfig},
try_with_handler, BoolOrDataConfig, Compiler, HandlerOpts,
};
use swc_common::{errors::ColorConfig, SourceMap};
use swc_common::{errors::ColorConfig, SourceMap, GLOBALS};
use swc_ecma_ast::EsVersion;
use swc_ecma_parser::{EsConfig, Syntax, TsConfig};
use swc_ecma_testing::{exec_node_js, JsExecOptions};
Expand Down Expand Up @@ -255,61 +255,63 @@ fn get_expected_stdout(input: &Path) -> Result<String, Error> {
let cm = Arc::new(SourceMap::default());
let c = Compiler::new(cm.clone());

try_with_handler(
cm.clone(),
HandlerOpts {
color: ColorConfig::Always,
skip_filename: true,
},
|handler| {
let fm = cm.load_file(input).context("failed to load file")?;

if let Ok(output) = stdout_of(&fm.src, NodeModuleType::Module) {
return Ok(output);
}
if let Ok(output) = stdout_of(&fm.src, NodeModuleType::CommonJs) {
return Ok(output);
}

let res = c
.process_js_file(
fm,
handler,
&Options {
config: Config {
jsc: JscConfig {
target: Some(EsVersion::Es2021),
syntax: Some(Syntax::Typescript(TsConfig {
decorators: true,
GLOBALS.set(&Default::default(), || {
try_with_handler(
cm.clone(),
HandlerOpts {
color: ColorConfig::Always,
skip_filename: true,
},
|handler| {
let fm = cm.load_file(input).context("failed to load file")?;

if let Ok(output) = stdout_of(&fm.src, NodeModuleType::Module) {
return Ok(output);
}
if let Ok(output) = stdout_of(&fm.src, NodeModuleType::CommonJs) {
return Ok(output);
}

let res = c
.process_js_file(
fm,
handler,
&Options {
config: Config {
jsc: JscConfig {
target: Some(EsVersion::Es2021),
syntax: Some(Syntax::Typescript(TsConfig {
decorators: true,
..Default::default()
})),
..Default::default()
})),
},
module: match input.extension() {
Some(ext) if ext == "ts" => {
Some(ModuleConfig::CommonJs(Default::default()))
}
Some(ext) if ext == "mjs" => None,
_ => None,
},
..Default::default()
},
module: match input.extension() {
Some(ext) if ext == "ts" => {
Some(ModuleConfig::CommonJs(Default::default()))
}
Some(ext) if ext == "mjs" => None,
_ => None,
},
..Default::default()
},
..Default::default()
)
.context("failed to process file")?;

let res = stdout_of(
&res.code,
match input.extension() {
Some(ext) if ext == "mjs" => NodeModuleType::Module,
_ => NodeModuleType::CommonJs,
},
)
.context("failed to process file")?;

let res = stdout_of(
&res.code,
match input.extension() {
Some(ext) if ext == "mjs" => NodeModuleType::Module,
_ => NodeModuleType::CommonJs,
},
)?;
)?;

Ok(res)
},
)
Ok(res)
},
)
})
}

/// Rename `foo/.bar/exec.js` => `foo/bar/exec.js`
Expand Down Expand Up @@ -350,51 +352,53 @@ fn test_file_with_opts(
let cm = Arc::new(SourceMap::default());
let c = Compiler::new(cm.clone());

try_with_handler(
cm.clone(),
HandlerOpts {
color: ColorConfig::Always,
..Default::default()
},
|handler| {
let fm = cm.load_file(entry).context("failed to load file")?;

let res = c
.process_js_file(fm, handler, opts)
.context("failed to process file")?;

println!(
"---- {} (#{}) ----\n{}",
ansi_term::Color::Green.bold().paint("Code"),
idx,
res.code
);
println!("external_helpers: {:?}", opts.config.jsc.external_helpers);
println!("target: {:?}", opts.config.jsc.target.unwrap());

let actual_stdout = stdout_of(
&res.code,
if entry.extension().unwrap() == "mjs" {
NodeModuleType::Module
} else {
NodeModuleType::CommonJs
},
)?;

assert_eq!(
expected_stdout,
actual_stdout,
"\n---- {} -----\n{}\n---- {} -----\n{:#?}",
ansi_term::Color::Red.paint("Actual"),
actual_stdout,
ansi_term::Color::Blue.paint("Options"),
opts
);

Ok(())
},
)
.with_context(|| format!("failed to compile with opts: {:#?}", opts))
GLOBALS.set(&Default::default(), || {
try_with_handler(
cm.clone(),
HandlerOpts {
color: ColorConfig::Always,
..Default::default()
},
|handler| {
let fm = cm.load_file(entry).context("failed to load file")?;

let res = c
.process_js_file(fm, handler, opts)
.context("failed to process file")?;

println!(
"---- {} (#{}) ----\n{}",
ansi_term::Color::Green.bold().paint("Code"),
idx,
res.code
);
println!("external_helpers: {:?}", opts.config.jsc.external_helpers);
println!("target: {:?}", opts.config.jsc.target.unwrap());

let actual_stdout = stdout_of(
&res.code,
if entry.extension().unwrap() == "mjs" {
NodeModuleType::Module
} else {
NodeModuleType::CommonJs
},
)?;

assert_eq!(
expected_stdout,
actual_stdout,
"\n---- {} -----\n{}\n---- {} -----\n{:#?}",
ansi_term::Color::Red.paint("Actual"),
actual_stdout,
ansi_term::Color::Blue.paint("Options"),
opts
);

Ok(())
},
)
.with_context(|| format!("failed to compile with opts: {:#?}", opts))
})
}

enum NodeModuleType {
Expand Down