diff --git a/crates/rspack_core/src/dependency/mod.rs b/crates/rspack_core/src/dependency/mod.rs index 6c0cfb42bd4..6373af41ea2 100644 --- a/crates/rspack_core/src/dependency/mod.rs +++ b/crates/rspack_core/src/dependency/mod.rs @@ -156,183 +156,3 @@ impl std::fmt::Debug for DependencyCondition { } } } - -// TODO: should move to rspack_plugin_javascript once we drop old treeshaking -pub mod needs_refactor { - use once_cell::sync::Lazy; - use regex::Regex; - use swc_core::{ - common::{EqIgnoreSpan, Spanned, SyntaxContext, DUMMY_SP}, - ecma::{ - ast::{ - Expr, ExprOrSpread, Id, Ident, ImportDecl, Lit, MemberExpr, MemberProp, MetaPropExpr, - MetaPropKind, ModuleExportName, NewExpr, - }, - atoms::Atom, - }, - }; - - use crate::SpanExt; - - static IMPORT_META: Lazy = Lazy::new(|| { - Expr::Member(MemberExpr { - span: DUMMY_SP, - obj: Box::new(Expr::MetaProp(MetaPropExpr { - span: DUMMY_SP, - kind: MetaPropKind::ImportMeta, - })), - prop: MemberProp::Ident(Ident { - span: DUMMY_SP, - sym: "url".into(), - optional: false, - }), - }) - }); - - pub fn match_new_url(new_expr: &NewExpr) -> Option<(u32, u32, String)> { - fn is_import_meta_url(expr: &Expr) -> bool { - Ident::within_ignored_ctxt(|| expr.eq_ignore_span(&IMPORT_META)) - } - - if matches!(&*new_expr.callee, Expr::Ident(Ident { sym, .. }) if sym == "URL") - && let Some(args) = &new_expr.args - && let (Some(first), Some(second)) = (args.first(), args.get(1)) - && let ( - ExprOrSpread { - spread: None, - expr: box Expr::Lit(Lit::Str(path)), - }, - ExprOrSpread { - spread: None, - expr: box expr, - }, - ) = (first, second) - && is_import_meta_url(expr) - { - return Some(( - path.span.real_lo(), - expr.span().real_hi(), - path.value.to_string(), - )); - } - None - } - - pub static WORKER_FROM_REGEX: Lazy = - Lazy::new(|| Regex::new(r"^(.+?)(\(\))?\s+from\s+(.+)$").expect("invalid regex")); - - #[derive(Debug, Default)] - pub struct WorkerSyntaxList { - variables: Vec, - globals: Vec, - } - - impl WorkerSyntaxList { - pub fn push(&mut self, syntax: WorkerSyntax) { - if syntax.ctxt.is_some() { - self.variables.push(syntax); - } else { - self.globals.push(syntax); - } - } - - fn find_worker_syntax(&self, ident: &Ident) -> Option<&WorkerSyntax> { - (self.variables.iter().chain(self.globals.iter())).find(|s| s.matches(ident)) - } - - pub fn match_new_worker(&self, new_expr: &NewExpr) -> bool { - matches!(&*new_expr.callee, Expr::Ident(ident) if self.find_worker_syntax(ident).is_some()) - } - } - - impl Extend for WorkerSyntaxList { - fn extend>(&mut self, iter: T) { - for i in iter { - self.push(i); - } - } - } - - #[derive(Debug, PartialEq, Eq)] - pub struct WorkerSyntax { - word: Atom, - ctxt: Option, - } - - impl WorkerSyntax { - pub fn new(word: Atom, ctxt: Option) -> Self { - Self { word, ctxt } - } - - pub fn matches(&self, ident: &Ident) -> bool { - if let Some(ctxt) = self.ctxt { - let (word, id_ctxt) = ident.to_id(); - word == self.word && id_ctxt == ctxt - } else { - self.word == ident.sym - } - } - } - - pub const DEFAULT_WORKER_SYNTAX: &[&str] = - &["Worker", "SharedWorker", "Worker from worker_threads"]; - - pub fn init_worker_syntax_scanner( - syntax: &'static [&'static str], - caps: &mut Vec<(&str, &str)>, - list: &mut WorkerSyntaxList, - ) { - for s in syntax { - if let Some(captures) = WORKER_FROM_REGEX.captures(s) - && let Some(ids) = captures.get(1) - && let Some(source) = captures.get(3) - { - caps.push((ids.as_str(), source.as_str())); - } else { - list.push(WorkerSyntax::new(Atom::from(*s), None)) - } - } - } - - pub fn collect_from_import_decl( - caps: &[(&str, &str)], - decl: &ImportDecl, - list: &mut WorkerSyntaxList, - ) { - let source = &*decl.src.value; - let found = caps - .iter() - .filter(|cap| cap.1 == source) - .flat_map(|cap| { - if cap.0 == "default" { - decl - .specifiers - .iter() - .filter_map(|spec| spec.as_default()) - .map(|spec| spec.local.to_id()) - .collect::>() - } else { - decl - .specifiers - .iter() - .filter_map(|spec| { - spec.as_named().filter(|named| { - if let Some(imported) = &named.imported { - let s = match imported { - ModuleExportName::Ident(s) => &s.sym, - ModuleExportName::Str(s) => &s.value, - }; - s == cap.0 - } else { - &*named.local.sym == cap.0 - } - }) - }) - .map(|spec| spec.local.to_id()) - .collect::>() - } - }) - .map(|pair| WorkerSyntax::new(pair.0, Some(pair.1))); - list.extend(found); - } -} diff --git a/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs b/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs index c40f56553dd..8ed433d75e7 100644 --- a/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs +++ b/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs @@ -2,7 +2,6 @@ use std::sync::Arc; use itertools::Itertools; use rspack_core::diagnostics::map_box_diagnostics_to_module_parse_diagnostics; -use rspack_core::needs_refactor::WorkerSyntaxList; use rspack_core::rspack_sources::{BoxSource, ReplaceSource, Source, SourceExt}; use rspack_core::{ render_init_fragments, AsyncDependenciesBlockIdentifier, BuildMetaExportsType, ChunkGraph, @@ -164,7 +163,6 @@ impl ParserAndGenerator for JavaScriptParserAndGenerator { }); let mut path_ignored_spans = PathIgnoredSpans::default(); - let mut worker_syntax_list = WorkerSyntaxList::default(); let ScanDependenciesResult { mut dependencies, @@ -177,7 +175,6 @@ impl ParserAndGenerator for JavaScriptParserAndGenerator { scan_dependencies( &fm, program, - &mut worker_syntax_list, resource_data, compiler_options, module_type, diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/drive.rs b/crates/rspack_plugin_javascript/src/parser_plugin/drive.rs index 6c1dc93ad9d..5ed3e068353 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/drive.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/drive.rs @@ -287,9 +287,10 @@ impl JavascriptParserPlugin for JavaScriptParserPluginDrive { &self, parser: &mut JavascriptParser, expr: &swc_core::ecma::ast::NewExpr, + for_name: &str, ) -> Option { for plugin in &self.plugins { - let res = plugin.new_expression(parser, expr); + let res = plugin.new_expression(parser, expr, for_name); // `SyncBailHook` if res.is_some() { return res; diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/harmony_import_dependency_parser_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/harmony_import_dependency_parser_plugin.rs index 0bb5351c7ea..03105fb5640 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/harmony_import_dependency_parser_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/harmony_import_dependency_parser_plugin.rs @@ -71,14 +71,14 @@ fn get_non_optional_member_chain_from_member(member: &MemberExpr, mut count: i32 pub struct HarmonyImportDependencyParserPlugin; -const HARMONY_SPECIFIER_TAG: &str = "_identifier__harmony_specifier_tag__"; +pub const HARMONY_SPECIFIER_TAG: &str = "_identifier__harmony_specifier_tag__"; #[derive(Debug, Clone)] -struct HarmonySpecifierData { - name: Atom, - source: Atom, - ids: Vec, - source_order: i32, +pub struct HarmonySpecifierData { + pub name: Atom, + pub source: Atom, + pub ids: Vec, + pub source_order: i32, } impl TagInfoData for HarmonySpecifierData { diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/mod.rs b/crates/rspack_plugin_javascript/src/parser_plugin/mod.rs index b95781e687e..8ef3025d957 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/mod.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/mod.rs @@ -26,8 +26,6 @@ mod url_plugin; mod use_strict_plugin; mod webpack_included_plugin; mod worker_plugin; -/// TODO: should move to rspack_plugin_javascript once we drop old treeshaking -mod worker_syntax_plugin; pub(crate) use self::api_plugin::APIPlugin; pub(crate) use self::check_var_decl::CheckVarDeclaratorIdent; @@ -57,7 +55,6 @@ pub(crate) use self::url_plugin::URLPlugin; pub(crate) use self::use_strict_plugin::UseStrictPlugin; pub(crate) use self::webpack_included_plugin::WebpackIsIncludedPlugin; pub(crate) use self::worker_plugin::WorkerPlugin; -pub(crate) use self::worker_syntax_plugin::WorkerSyntaxScanner; pub static JS_DEFAULT_KEYWORD: once_cell::sync::Lazy = once_cell::sync::Lazy::new(|| swc_core::atoms::atom!("default")); diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/trait.rs b/crates/rspack_plugin_javascript/src/parser_plugin/trait.rs index 18907c537bb..d37c5dd5980 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/trait.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/trait.rs @@ -198,7 +198,12 @@ pub trait JavascriptParserPlugin { None } - fn new_expression(&self, _parser: &mut JavascriptParser, _expr: &NewExpr) -> Option { + fn new_expression( + &self, + _parser: &mut JavascriptParser, + _expr: &NewExpr, + _for_name: &str, + ) -> Option { None } diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/url_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/url_plugin.rs index fa4c6671015..f8904b3e185 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/url_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/url_plugin.rs @@ -1,22 +1,59 @@ use rspack_core::SpanExt; +use swc_core::{ + common::Spanned, + ecma::ast::{Expr, ExprOrSpread, MetaPropKind, NewExpr}, +}; use super::JavascriptParserPlugin; use crate::{dependency::URLDependency, visitors::JavascriptParser}; +pub fn get_url_request( + parser: &mut JavascriptParser, + expr: &NewExpr, +) -> Option<(String, u32, u32)> { + if let Some(args) = &expr.args + && let Some(ExprOrSpread { + spread: None, + expr: arg1, + }) = args.first() + && let Some(ExprOrSpread { + spread: None, + expr: box Expr::Member(arg2), + }) = args.get(1) + { + let chain = parser.extract_member_expression_chain(arg2); + if let Some(meta) = chain.object.as_meta_prop() + && matches!(meta.kind, MetaPropKind::ImportMeta) + && chain.members.len() == 1 + && matches!(chain.members.first(), Some(member) if member == "url") + { + return parser + .evaluate_expression(arg1) + .as_string() + .map(|req| (req, arg1.span().real_lo(), arg2.span().real_hi())); + } + } + None +} + pub struct URLPlugin { pub relative: bool, } impl JavascriptParserPlugin for URLPlugin { + fn can_rename(&self, _parser: &mut JavascriptParser, for_name: &str) -> Option { + (for_name == "URL").then_some(true) + } + fn new_expression( &self, parser: &mut JavascriptParser, - expr: &swc_core::ecma::ast::NewExpr, + expr: &NewExpr, + for_name: &str, ) -> Option { - if parser.worker_syntax_list.match_new_worker(expr) { - // skip `new Worker(new Url,)` - None - } else if let Some((start, end, request)) = rspack_core::needs_refactor::match_new_url(expr) { + if for_name == "URL" + && let Some((request, start, end)) = get_url_request(parser, expr) + { parser.dependencies.push(Box::new(URLDependency::new( start, end, diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs index 7687322a6a8..9b761b51884 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs @@ -1,18 +1,28 @@ use std::hash::Hash; +use itertools::Itertools; use rspack_core::{ AsyncDependenciesBlock, ConstDependency, DependencyLocation, EntryOptions, ErrorSpan, GroupOptions, SpanExt, }; use rspack_hash::RspackHash; -use swc_core::common::{Span, Spanned}; -use swc_core::ecma::ast::{Expr, ExprOrSpread, NewExpr}; +use rustc_hash::FxHashSet; +use swc_core::{ + common::{Span, Spanned}, + ecma::ast::{Expr, ExprOrSpread, NewExpr}, +}; -use super::JavascriptParserPlugin; -use crate::dependency::WorkerDependency; -use crate::utils::get_literal_str_by_obj_prop; -use crate::visitors::JavascriptParser; -use crate::webpack_comment::try_extract_webpack_magic_comment; +use super::{ + harmony_import_dependency_parser_plugin::{HarmonySpecifierData, HARMONY_SPECIFIER_TAG}, + url_plugin::get_url_request, + JavascriptParserPlugin, +}; +use crate::{ + dependency::WorkerDependency, + utils::get_literal_str_by_obj_prop, + visitors::{JavascriptParser, TagInfoData}, + webpack_comment::try_extract_webpack_magic_comment, +}; #[derive(Debug)] struct ParsedNewWorkerPath { @@ -58,137 +68,169 @@ fn parse_new_worker_options_from_comments( }) } -impl<'parser> JavascriptParser<'parser> { - fn add_dependencies( - &mut self, - new_expr: &NewExpr, - parsed_path: ParsedNewWorkerPath, - parsed_options: Option, - ) { - let output_options = &self.compiler_options.output; - let mut hasher = RspackHash::from(output_options); - self.module_identifier.hash(&mut hasher); - self.worker_index.hash(&mut hasher); - self.worker_index += 1; - let digest = hasher.digest(&output_options.hash_digest); - let runtime = digest - .rendered(output_options.hash_digest_length) - .to_owned(); - let range = parsed_options.as_ref().and_then(|options| options.range); - let name = parsed_options.and_then(|options| options.name); - let output_module = output_options.module; - let span = ErrorSpan::from(new_expr.span); - let dep = Box::new(WorkerDependency::new( - parsed_path.range.0, - parsed_path.range.1, - parsed_path.value, - output_options.worker_public_path.clone(), - Some(span), - )); - let mut block = AsyncDependenciesBlock::new( - *self.module_identifier, - Some(DependencyLocation::new(span.start, span.end)), - None, - vec![dep], - ); - block.set_group_options(GroupOptions::Entrypoint(Box::new(EntryOptions { - name, - runtime: Some(runtime.into()), - chunk_loading: Some(output_options.worker_chunk_loading.clone()), - async_chunks: None, - public_path: None, - base_uri: None, - filename: None, - library: None, - depend_on: None, - }))); +fn add_dependencies( + parser: &mut JavascriptParser, + new_expr: &NewExpr, + parsed_path: ParsedNewWorkerPath, + parsed_options: Option, +) { + let output_options = &parser.compiler_options.output; + let mut hasher = RspackHash::from(output_options); + parser.module_identifier.hash(&mut hasher); + parser.worker_index.hash(&mut hasher); + parser.worker_index += 1; + let digest = hasher.digest(&output_options.hash_digest); + let runtime = digest + .rendered(output_options.hash_digest_length) + .to_owned(); + let range = parsed_options.as_ref().and_then(|options| options.range); + let name = parsed_options.and_then(|options| options.name); + let output_module = output_options.module; + let span = ErrorSpan::from(new_expr.span); + let dep = Box::new(WorkerDependency::new( + parsed_path.range.0, + parsed_path.range.1, + parsed_path.value, + output_options.worker_public_path.clone(), + Some(span), + )); + let mut block = AsyncDependenciesBlock::new( + *parser.module_identifier, + Some(DependencyLocation::new(span.start, span.end)), + None, + vec![dep], + ); + block.set_group_options(GroupOptions::Entrypoint(Box::new(EntryOptions { + name, + runtime: Some(runtime.into()), + chunk_loading: Some(output_options.worker_chunk_loading.clone()), + async_chunks: None, + public_path: None, + base_uri: None, + filename: None, + library: None, + depend_on: None, + }))); - self.blocks.push(block); - if let Some(range) = range { - self - .presentational_dependencies - .push(Box::new(ConstDependency::new( - range.0, - range.0, - "Object.assign({}, ".into(), - None, - ))); - self - .presentational_dependencies - .push(Box::new(ConstDependency::new( - range.1, - range.1, - format!( - ", {{ type: {} }})", - if output_module { - "\"module\"" - } else { - "undefined" - } - ) - .into(), - None, - ))); - } + parser.blocks.push(block); + if let Some(range) = range { + parser + .presentational_dependencies + .push(Box::new(ConstDependency::new( + range.0, + range.0, + "Object.assign({}, ".into(), + None, + ))); + parser + .presentational_dependencies + .push(Box::new(ConstDependency::new( + range.1, + range.1, + format!( + ", {{ type: {} }})", + if output_module { + "\"module\"" + } else { + "undefined" + } + ) + .into(), + None, + ))); } +} - fn parse_new_worker( - &mut self, - new_expr: &NewExpr, - ) -> Option<(ParsedNewWorkerPath, Option)> { - if self.worker_syntax_list.match_new_worker(new_expr) - && let Some(args) = &new_expr.args - && let Some(expr_or_spread) = args.first() - && let ExprOrSpread { - spread: None, - expr: box Expr::New(new_url_expr), - } = expr_or_spread - && let Some((start, end, request)) = rspack_core::needs_refactor::match_new_url(new_url_expr) - { - let path = ParsedNewWorkerPath { - range: (start, end), - value: request, - }; - let options = args - .get(1) - // new Worker(new URL("worker.js"), options) - .map(parse_new_worker_options) - .or_else(|| { - // new Worker(new URL(/* options */ "worker.js")) - new_url_expr - .args - .as_ref() - .and_then(|args| args.first()) - .and_then(|n| { - parse_new_worker_options_from_comments(self, n.span(), new_url_expr.span()) - }) - }) - .or_else(|| { - // new Worker(/* options */ new URL("worker.js")) - parse_new_worker_options_from_comments(self, expr_or_spread.span(), new_expr.span()) - }); - Some((path, options)) - } else { - None - } +fn parse_new_worker( + parser: &mut JavascriptParser, + new_expr: &NewExpr, +) -> Option<(ParsedNewWorkerPath, Option)> { + if let Some(args) = &new_expr.args + && let Some(expr_or_spread) = args.first() + && let ExprOrSpread { + spread: None, + expr: box Expr::New(new_url_expr), + } = expr_or_spread + && let Some((request, start, end)) = get_url_request(parser, new_url_expr) + { + let path = ParsedNewWorkerPath { + range: (start, end), + value: request, + }; + let options = args + .get(1) + // new Worker(new URL("worker.js"), options) + .map(parse_new_worker_options) + .or_else(|| { + // new Worker(new URL(/* options */ "worker.js")) + new_url_expr + .args + .as_ref() + .and_then(|args| args.first()) + .and_then(|n| { + parse_new_worker_options_from_comments(parser, n.span(), new_url_expr.span()) + }) + }) + .or_else(|| { + // new Worker(/* options */ new URL("worker.js")) + parse_new_worker_options_from_comments(parser, expr_or_spread.span(), new_expr.span()) + }); + Some((path, options)) + } else { + None } } -/// `new Worker(new URL("./foo.worker.js", import.meta.url));` -pub struct WorkerPlugin; +pub struct WorkerPlugin { + new_syntax: FxHashSet, + // call_syntax: FxHashSet, + from_new_syntax: FxHashSet<(String, String)>, + // from_call_syntax: FxHashSet<(String, String)>, +} + +impl WorkerPlugin { + pub fn new(/* syntax_list: &[&str] */) -> Self { + Self { + new_syntax: FxHashSet::from_iter(["Worker".into(), "SharedWorker".into()]), + // call_syntax: FxHashSet::default(), + from_new_syntax: FxHashSet::from_iter([("Worker".into(), "worker_threads".into())]), + // from_call_syntax: FxHashSet::default(), + } + } +} impl JavascriptParserPlugin for WorkerPlugin { fn new_expression( &self, parser: &mut JavascriptParser, new_expr: &swc_core::ecma::ast::NewExpr, + for_name: &str, ) -> Option { - parser - .parse_new_worker(new_expr) - .map(|(parsed_path, parsed_options)| { - parser.add_dependencies(new_expr, parsed_path, parsed_options); - parser.walk_expression(&new_expr.callee); - true - }) + if for_name == HARMONY_SPECIFIER_TAG { + let tag_info = parser + .definitions_db + .expect_get_tag_info(&parser.current_tag_info?); + let settings = HarmonySpecifierData::downcast(tag_info.data.clone()?); + let ids = settings.ids.iter().map(|id| id.as_str()).join("."); + if self + .from_new_syntax + .contains(&(ids, settings.source.to_string())) + { + return parse_new_worker(parser, new_expr).map(|(parsed_path, parsed_options)| { + add_dependencies(parser, new_expr, parsed_path, parsed_options); + parser.walk_expression(&new_expr.callee); + true + }); + } + return None; + } + if !self.new_syntax.contains(for_name) { + return None; + } + parse_new_worker(parser, new_expr).map(|(parsed_path, parsed_options)| { + add_dependencies(parser, new_expr, parsed_path, parsed_options); + parser.walk_expression(&new_expr.callee); + true + }) } } diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/worker_syntax_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/worker_syntax_plugin.rs deleted file mode 100644 index c05a0d665c8..00000000000 --- a/crates/rspack_plugin_javascript/src/parser_plugin/worker_syntax_plugin.rs +++ /dev/null @@ -1,31 +0,0 @@ -use rspack_core::needs_refactor::WorkerSyntaxList; -use rspack_core::needs_refactor::{collect_from_import_decl, init_worker_syntax_scanner}; - -use super::JavascriptParserPlugin; -use crate::visitors::JavascriptParser; - -pub struct WorkerSyntaxScanner { - caps: Vec<(&'static str, &'static str)>, -} - -impl WorkerSyntaxScanner { - pub fn new(syntax: &'static [&'static str], list: &mut WorkerSyntaxList) -> Self { - let mut caps = Vec::new(); - init_worker_syntax_scanner(syntax, &mut caps, list); - Self { caps } - } -} - -impl JavascriptParserPlugin for WorkerSyntaxScanner { - fn pre_module_declaration( - &self, - parser: &mut JavascriptParser, - decl: &swc_core::ecma::ast::ModuleDecl, - ) -> Option { - let Some(decl) = decl.as_import() else { - return None; - }; - collect_from_import_decl(&self.caps, decl, parser.worker_syntax_list); - None - } -} diff --git a/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs b/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs index 30ac83b639e..35ad6cc6d07 100644 --- a/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs +++ b/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs @@ -4,7 +4,6 @@ mod parser; mod util; use rspack_ast::javascript::Program; -use rspack_core::needs_refactor::WorkerSyntaxList; use rspack_core::{ AsyncDependenciesBlock, BoxDependency, BoxDependencyTemplate, BuildInfo, ParserOptions, }; @@ -67,7 +66,6 @@ pub enum ExtraSpanInfo { pub fn scan_dependencies( source_file: &SourceFile, program: &Program, - worker_syntax_list: &mut WorkerSyntaxList, resource_data: &ResourceData, compiler_options: &CompilerOptions, module_type: &ModuleType, @@ -87,7 +85,6 @@ pub fn scan_dependencies( program.comments.as_ref().map(|c| c as &dyn Comments), &module_identifier, module_type, - worker_syntax_list, resource_data, build_meta, build_info, diff --git a/crates/rspack_plugin_javascript/src/visitors/dependency/parser/mod.rs b/crates/rspack_plugin_javascript/src/visitors/dependency/parser/mod.rs index 6810f82fe6e..440cb24154b 100644 --- a/crates/rspack_plugin_javascript/src/visitors/dependency/parser/mod.rs +++ b/crates/rspack_plugin_javascript/src/visitors/dependency/parser/mod.rs @@ -9,7 +9,6 @@ use std::rc::Rc; use bitflags::bitflags; pub use call_hooks_name::CallHooksName; -use rspack_core::needs_refactor::WorkerSyntaxList; use rspack_core::{ AsyncDependenciesBlock, BoxDependency, BuildInfo, BuildMeta, DependencyTemplate, JavascriptParserOptions, ModuleIdentifier, ResourceData, @@ -43,10 +42,10 @@ pub trait TagInfoData { #[derive(Debug)] pub struct ExtractedMemberExpressionChainData { - object: Expr, - members: Vec, - members_optionals: Vec, - member_ranges: Vec, + pub object: Expr, + pub members: Vec, + pub members_optionals: Vec, + pub member_ranges: Vec, } bitflags! { @@ -222,8 +221,6 @@ pub struct JavascriptParser<'parser> { // TODO: remove `rewrite_usage_span` pub(crate) rewrite_usage_span: FxHashMap, pub(crate) comments: Option<&'parser dyn Comments>, - // TODO: remove `worker_syntax_list` - pub(crate) worker_syntax_list: &'parser mut WorkerSyntaxList, pub(crate) worker_index: u32, pub(crate) build_meta: &'parser mut BuildMeta, pub(crate) build_info: &'parser mut BuildInfo, @@ -240,10 +237,6 @@ pub struct JavascriptParser<'parser> { pub(crate) parser_exports_state: Option, // TODO: delete `enter_call` pub(crate) enter_call: u32, - // TODO: delete `enter_new_expr` - pub(crate) enter_new_expr: bool, - // TODO: delete `enter_callee` - pub(crate) enter_callee: bool, pub(crate) member_expr_in_optional_chain: bool, pub(crate) stmt_level: u32, pub(crate) last_stmt_is_expr_stmt: bool, @@ -273,7 +266,6 @@ impl<'parser> JavascriptParser<'parser> { comments: Option<&'parser dyn Comments>, module_identifier: &'parser ModuleIdentifier, module_type: &'parser ModuleType, - worker_syntax_list: &'parser mut WorkerSyntaxList, resource_data: &'parser ResourceData, build_meta: &'parser mut BuildMeta, build_info: &'parser mut BuildInfo, @@ -298,10 +290,6 @@ impl<'parser> JavascriptParser<'parser> { plugins.push(Box::new( parser_plugin::RequireContextDependencyParserPlugin, )); - plugins.push(Box::new(parser_plugin::WorkerSyntaxScanner::new( - rspack_core::needs_refactor::DEFAULT_WORKER_SYNTAX, - worker_syntax_list, - ))); plugins.push(Box::new(parser_plugin::CompatibilityPlugin)); if module_type.is_js_auto() || module_type.is_js_esm() { @@ -364,7 +352,7 @@ impl<'parser> JavascriptParser<'parser> { relative: matches!(parse_url, JavascriptParserUrl::Relative), })); } - plugins.push(Box::new(parser_plugin::WorkerPlugin)); + plugins.push(Box::new(parser_plugin::WorkerPlugin::new())); } let plugin_drive = Rc::new(JavaScriptParserPluginDrive::new(plugins)); @@ -388,7 +376,6 @@ impl<'parser> JavascriptParser<'parser> { definitions: db.create(), definitions_db: db, plugin_drive, - worker_syntax_list, resource_data, build_meta, build_info, @@ -402,8 +389,6 @@ impl<'parser> JavascriptParser<'parser> { module_identifier, import_map, rewrite_usage_span, - enter_new_expr: false, - enter_callee: false, member_expr_in_optional_chain: false, properties_in_destructuring: Default::default(), semicolons, @@ -649,7 +634,7 @@ impl<'parser> JavascriptParser<'parser> { ) } - fn extract_member_expression_chain( + pub fn extract_member_expression_chain( &self, expr: &MemberExpr, ) -> ExtractedMemberExpressionChainData { diff --git a/crates/rspack_plugin_javascript/src/visitors/dependency/parser/walk.rs b/crates/rspack_plugin_javascript/src/visitors/dependency/parser/walk.rs index 9c67a2152ad..9f815cacdda 100644 --- a/crates/rspack_plugin_javascript/src/visitors/dependency/parser/walk.rs +++ b/crates/rspack_plugin_javascript/src/visitors/dependency/parser/walk.rs @@ -521,18 +521,10 @@ impl<'parser> JavascriptParser<'parser> { } fn walk_tagged_template_expression(&mut self, expr: &TaggedTpl) { - // every time into new tagged tpl expr, reset enter callee - let old = self.enter_new_expr; - self.enter_new_expr = false; - self.enter_callee = true; - self.in_tagged_template_tag = true; self.walk_expression(&expr.tag); self.in_tagged_template_tag = false; - self.enter_new_expr = old; - self.enter_callee = false; - let exprs = expr.tpl.exprs.iter().map(|expr| &**expr); self.walk_expressions(exprs); } @@ -613,21 +605,29 @@ impl<'parser> JavascriptParser<'parser> { } fn walk_new_expression(&mut self, expr: &NewExpr) { - let old = self.enter_new_expr; - self.enter_new_expr = true; - - // TODO: `callHooksForExpression` - if self - .plugin_drive - .clone() - .new_expression(self, expr) - .unwrap_or_default() + if let Some(MemberExpressionInfo::Expression(info)) = + self.get_member_expression_info_from_expr(&expr.callee, AllowedMemberTypes::Expression) { - self.enter_new_expr = old; - return; + let result = if info.members.is_empty() { + info.root_info.call_hooks_name(self, |parser, for_name| { + parser + .plugin_drive + .clone() + .new_expression(parser, expr, for_name) + }) + } else { + info.name.call_hooks_name(self, |parser, for_name| { + parser + .plugin_drive + .clone() + .new_expression(parser, expr, for_name) + }) + }; + if result.unwrap_or_default() { + return; + } } self.walk_expression(&expr.callee); - self.enter_new_expr = old; if let Some(args) = &expr.args { self.walk_expr_or_spread(args); } @@ -877,10 +877,6 @@ impl<'parser> JavascriptParser<'parser> { } fn walk_call_expression(&mut self, expr: &CallExpr) { - // every time into new call_expr, reset enter callee - let old = self.enter_new_expr; - self.enter_new_expr = false; - self.enter_callee = true; self.enter_call += 1; fn is_simple_function(params: &[Param]) -> bool { @@ -943,8 +939,6 @@ impl<'parser> JavascriptParser<'parser> { .unwrap_or_default() { self.enter_call -= 1; - self.enter_new_expr = old; - self.enter_callee = false; return; } let evaluated_callee = self.evaluate_expression(callee); @@ -978,8 +972,6 @@ impl<'parser> JavascriptParser<'parser> { { /* result1 */ self.enter_call -= 1; - self.enter_new_expr = old; - self.enter_callee = false; return; } @@ -989,8 +981,6 @@ impl<'parser> JavascriptParser<'parser> { { /* result2 */ self.enter_call -= 1; - self.enter_new_expr = old; - self.enter_callee = false; return; } } @@ -1014,15 +1004,11 @@ impl<'parser> JavascriptParser<'parser> { .unwrap_or_default() { self.enter_call -= 1; - self.enter_new_expr = old; - self.enter_callee = false; return; } } Callee::Super(_) => {} // Do nothing about super, same as webpack } - self.enter_new_expr = old; - self.enter_callee = false; self.walk_expr_or_spread(&expr.args); self.enter_call -= 1; diff --git a/webpack-test/configCases/worker/node-worker-hmr/test.filter.js b/webpack-test/configCases/worker/node-worker-hmr/test.filter.js index fa210156b31..7039623344e 100644 --- a/webpack-test/configCases/worker/node-worker-hmr/test.filter.js +++ b/webpack-test/configCases/worker/node-worker-hmr/test.filter.js @@ -1,7 +1,5 @@ -// var supportsWorker = require("../../../helpers/supportsWorker"); +var supportsWorker = require("../../../helpers/supportsWorker"); -// module.exports = function (config) { -// return supportsWorker(); -// }; - -module.exports = () => {return 'HMR plugin'} +module.exports = function (config) { + return supportsWorker(); +}; diff --git a/webpack-test/configCases/worker/node-worker/test.filter.js b/webpack-test/configCases/worker/node-worker/test.filter.js deleted file mode 100644 index f5df34cde0f..00000000000 --- a/webpack-test/configCases/worker/node-worker/test.filter.js +++ /dev/null @@ -1,7 +0,0 @@ -// var supportsWorker = require("../../../helpers/supportsWorker"); - -// module.exports = function (config) { -// return supportsWorker(); -// }; - -module.exports = () => {return 'needs compile time evaluateExpression'} diff --git a/webpack-test/configCases/worker/web-worker/test.filter.js b/webpack-test/configCases/worker/web-worker/test.filter.js index fc4790e0a8a..7039623344e 100644 --- a/webpack-test/configCases/worker/web-worker/test.filter.js +++ b/webpack-test/configCases/worker/web-worker/test.filter.js @@ -1,8 +1,5 @@ +var supportsWorker = require("../../../helpers/supportsWorker"); -// var supportsWorker = require("../../../helpers/supportsWorker"); - -// module.exports = function (config) { -// return supportsWorker(); -// }; - -module.exports = () => {return true} \ No newline at end of file +module.exports = function (config) { + return supportsWorker(); +};