Skip to content

Commit 1c5ec4b

Browse files
authored
refactor: check neutral platform (#12534)
* refactor: add platform to compiler * refactor: add platform to compiler
1 parent 650a863 commit 1c5ec4b

File tree

25 files changed

+251
-34
lines changed

25 files changed

+251
-34
lines changed

crates/node_binding/napi-binding.d.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ export declare class JsCompilation {
326326
}
327327

328328
export declare class JsCompiler {
329-
constructor(compilerPath: string, options: RawOptions, builtinPlugins: Array<BuiltinPlugin>, registerJsTaps: RegisterJsTaps, outputFilesystem: ThreadsafeNodeFS, intermediateFilesystem: ThreadsafeNodeFS | undefined | null, inputFilesystem: ThreadsafeNodeFS | undefined | null, resolverFactoryReference: JsResolverFactory, unsafeFastDrop: boolean)
329+
constructor(compilerPath: string, options: RawOptions, builtinPlugins: Array<BuiltinPlugin>, registerJsTaps: RegisterJsTaps, outputFilesystem: ThreadsafeNodeFS, intermediateFilesystem: ThreadsafeNodeFS | undefined | null, inputFilesystem: ThreadsafeNodeFS | undefined | null, resolverFactoryReference: JsResolverFactory, unsafeFastDrop: boolean, platform: RawCompilerPlatform)
330330
setNonSkippableRegisters(kinds: Array<RegisterJsTapKind>): void
331331
/** Build with the given option passed to the constructor */
332332
build(callback: (err: null | Error) => void): void
@@ -1838,6 +1838,15 @@ export interface RawCircularDependencyRspackPluginOptions {
18381838
onEnd?: () => void
18391839
}
18401840

1841+
export interface RawCompilerPlatform {
1842+
web?: boolean | null
1843+
browser?: boolean | null
1844+
webworker?: boolean | null
1845+
node?: boolean | null
1846+
nwjs?: boolean | null
1847+
electron?: boolean | null
1848+
}
1849+
18411850
export interface RawConsumeOptions {
18421851
key: string
18431852
import?: string

crates/rspack/src/builder/builder_context.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#![allow(clippy::enum_variant_names)]
22
use enum_tag::EnumTag;
33
use rspack_core::{
4-
BoxPlugin, ChunkLoadingType, CompilerOptions, EntryOptions, ExternalItem, ExternalType,
5-
LibraryType, PluginExt as _, WasmLoadingType,
4+
BoxPlugin, ChunkLoadingType, CompilerOptions, CompilerPlatform, EntryOptions, ExternalItem,
5+
ExternalType, LibraryType, PluginExt as _, WasmLoadingType,
66
};
77

88
/// Options of builtin plugins
@@ -100,9 +100,15 @@ pub(super) enum BuiltinPluginOptions {
100100
#[derive(Default, Debug)]
101101
pub struct BuilderContext {
102102
pub(super) plugins: Vec<BuiltinPluginOptions>,
103+
pub(super) platform: CompilerPlatform,
103104
}
104105

105106
impl BuilderContext {
107+
/// Take platform from the context
108+
pub fn take_platform(&mut self) -> CompilerPlatform {
109+
std::mem::take(&mut self.platform)
110+
}
111+
106112
/// Take plugins from the context.
107113
///
108114
/// The plugins are sorted by their tag.

crates/rspack/src/builder/mod.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ use externals::ExternalsPresets;
3838
use indexmap::IndexMap;
3939
use rspack_core::{
4040
AssetParserDataUrl, AssetParserDataUrlOptions, AssetParserOptions, BoxPlugin, ByDependency,
41-
CacheOptions, ChunkLoading, ChunkLoadingType, CleanOptions, Compiler, CompilerOptions, Context,
42-
CrossOriginLoading, CssAutoGeneratorOptions, CssAutoParserOptions, CssExportsConvention,
43-
CssGeneratorOptions, CssModuleGeneratorOptions, CssModuleParserOptions, CssParserOptions,
44-
DynamicImportMode, EntryDescription, EntryOptions, EntryRuntime, Environment,
41+
CacheOptions, ChunkLoading, ChunkLoadingType, CleanOptions, Compiler, CompilerOptions,
42+
CompilerPlatform, Context, CrossOriginLoading, CssAutoGeneratorOptions, CssAutoParserOptions,
43+
CssExportsConvention, CssGeneratorOptions, CssModuleGeneratorOptions, CssModuleParserOptions,
44+
CssParserOptions, DynamicImportMode, EntryDescription, EntryOptions, EntryRuntime, Environment,
4545
ExperimentCacheOptions, Experiments, ExternalItem, ExternalType, Filename, GeneratorOptions,
4646
GeneratorOptionsMap, JavascriptParserCommonjsExportsOption, JavascriptParserCommonjsOptions,
4747
JavascriptParserOptions, JavascriptParserOrder, JavascriptParserUrl, JsonGeneratorOptions,
@@ -448,6 +448,7 @@ impl CompilerBuilder {
448448
let mut builder_context = BuilderContext::default();
449449
let compiler_options = self.options_builder.build(&mut builder_context)?;
450450
let mut plugins = builder_context.take_plugins(&compiler_options);
451+
let platform = builder_context.take_platform();
451452
plugins.append(&mut self.plugins);
452453

453454
let input_filesystem = self.input_filesystem.take();
@@ -465,6 +466,7 @@ impl CompilerBuilder {
465466
None,
466467
None,
467468
compiler_context,
469+
Arc::new(platform),
468470
))
469471
}
470472
}
@@ -913,6 +915,7 @@ impl CompilerOptionsBuilder {
913915
vec!["web".to_string()]
914916
});
915917
let target_properties = get_targets_properties(&target, &context);
918+
builder_context.platform = CompilerPlatform::from(&target_properties);
916919

917920
let development = matches!(self.mode, Some(Mode::Development));
918921
let production = matches!(self.mode, Some(Mode::Production) | None);

crates/rspack/src/builder/target.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use rspack_browserslist::load_browserslist;
2-
use rspack_core::Context;
2+
use rspack_core::{CompilerPlatform, Context};
33

44
/// Targets type.
55
pub type Targets = Vec<String>;
@@ -128,6 +128,19 @@ impl TargetProperties {
128128
}
129129
}
130130

131+
impl From<&TargetProperties> for CompilerPlatform {
132+
fn from(value: &TargetProperties) -> Self {
133+
Self {
134+
web: value.web,
135+
browser: value.browser,
136+
webworker: value.webworker,
137+
node: value.node,
138+
nwjs: value.nwjs,
139+
electron: value.electron,
140+
}
141+
}
142+
}
143+
131144
fn version_dependent(
132145
major: u32,
133146
minor: Option<u32>,

crates/rspack/tests/snapshots/defaults__default_options-2.snap

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,24 @@ BuilderContext {
5252
EnsureChunkConditionsPlugin,
5353
WorkerPlugin,
5454
],
55+
platform: CompilerPlatform {
56+
web: Some(
57+
true,
58+
),
59+
browser: Some(
60+
true,
61+
),
62+
webworker: Some(
63+
false,
64+
),
65+
node: Some(
66+
false,
67+
),
68+
nwjs: Some(
69+
false,
70+
),
71+
electron: Some(
72+
false,
73+
),
74+
},
5575
}

crates/rspack_binding_api/src/lib.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ mod normal_module_factory;
8282
mod options;
8383
mod panic;
8484
mod path_data;
85+
mod platform;
8586
mod plugins;
8687
mod raw_options;
8788
mod resolver;
@@ -109,7 +110,8 @@ use napi::{CallContext, bindgen_prelude::*};
109110
pub use raw_options::{CustomPluginBuilder, register_custom_plugin};
110111
use rspack_collections::UkeyMap;
111112
use rspack_core::{
112-
BoxDependency, Compilation, CompilerId, EntryOptions, ModuleIdentifier, PluginExt,
113+
BoxDependency, Compilation, CompilerId, CompilerPlatform, EntryOptions, ModuleIdentifier,
114+
PluginExt,
113115
};
114116
use rspack_error::Diagnostic;
115117
use rspack_fs::{IntermediateFileSystem, NativeFileSystem, ReadableFileSystem};
@@ -127,6 +129,7 @@ use crate::{
127129
error::{ErrorCode, RspackResultToNapiResultExt},
128130
fs_node::{HybridFileSystem, NodeFileSystem, ThreadsafeNodeFS},
129131
module::ModuleObject,
132+
platform::RawCompilerPlatform,
130133
plugins::{
131134
JsCleanupPlugin, JsHooksAdapterPlugin, RegisterJsTapKind, RegisterJsTaps, buildtime_plugins,
132135
},
@@ -188,6 +191,7 @@ impl JsCompiler {
188191
input_filesystem: Option<ThreadsafeNodeFS>,
189192
mut resolver_factory_reference: Reference<JsResolverFactory>,
190193
unsafe_fast_drop: bool,
194+
platform: RawCompilerPlatform,
191195
) -> Result<Self> {
192196
tracing::info!(name:"rspack_version", version = rspack_workspace::rspack_pkg_version!());
193197
tracing::info!(name:"raw_options", options=?&options);
@@ -296,6 +300,8 @@ impl JsCompiler {
296300
None
297301
};
298302

303+
let platform = Arc::new(CompilerPlatform::from(platform));
304+
299305
let rspack = rspack_core::Compiler::new(
300306
compiler_path,
301307
compiler_options,
@@ -311,6 +317,7 @@ impl JsCompiler {
311317
Some(resolver_factory),
312318
Some(loader_resolver_factory),
313319
Some(compiler_context.clone()),
320+
platform,
314321
);
315322

316323
Ok(Self {
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
use napi::{Either, bindgen_prelude::Null};
2+
use napi_derive::napi;
3+
use rspack_core::CompilerPlatform;
4+
5+
#[derive(Debug)]
6+
#[napi(object, object_to_js = false)]
7+
pub struct RawCompilerPlatform {
8+
pub web: Option<Either<bool, Null>>,
9+
pub browser: Option<Either<bool, Null>>,
10+
pub webworker: Option<Either<bool, Null>>,
11+
pub node: Option<Either<bool, Null>>,
12+
pub nwjs: Option<Either<bool, Null>>,
13+
pub electron: Option<Either<bool, Null>>,
14+
}
15+
16+
impl From<RawCompilerPlatform> for CompilerPlatform {
17+
fn from(value: RawCompilerPlatform) -> Self {
18+
Self {
19+
web: from_raw_platform(value.web),
20+
browser: from_raw_platform(value.browser),
21+
webworker: from_raw_platform(value.webworker),
22+
node: from_raw_platform(value.node),
23+
nwjs: from_raw_platform(value.nwjs),
24+
electron: from_raw_platform(value.electron),
25+
}
26+
}
27+
}
28+
29+
fn from_raw_platform(v: Option<Either<bool, Null>>) -> Option<bool> {
30+
match v {
31+
Some(Either::A(v)) => Some(v),
32+
_ => None,
33+
}
34+
}

crates/rspack_core/src/compilation/build_module_graph/graph_updater/repair/context.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use rustc_hash::FxHashMap as HashMap;
66

77
use super::BuildModuleGraphArtifact;
88
use crate::{
9-
Compilation, CompilationId, CompilerId, CompilerOptions, DependencyTemplate,
9+
Compilation, CompilationId, CompilerId, CompilerOptions, CompilerPlatform, DependencyTemplate,
1010
DependencyTemplateType, DependencyType, ModuleFactory, ResolverFactory, RuntimeTemplate,
1111
SharedPluginDriver,
1212
incremental::Incremental,
@@ -25,6 +25,7 @@ pub struct TaskContext {
2525
pub intermediate_fs: Arc<dyn IntermediateFileSystem>,
2626
pub output_fs: Arc<dyn WritableFileSystem>,
2727
pub compiler_options: Arc<CompilerOptions>,
28+
pub platform: Arc<CompilerPlatform>,
2829
pub resolver_factory: Arc<ResolverFactory>,
2930
pub loader_resolver_factory: Arc<ResolverFactory>,
3031
pub old_cache: Arc<OldCache>,
@@ -43,6 +44,7 @@ impl TaskContext {
4344
plugin_driver: compilation.plugin_driver.clone(),
4445
buildtime_plugin_driver: compilation.buildtime_plugin_driver.clone(),
4546
compiler_options: compilation.options.clone(),
47+
platform: compilation.platform.clone(),
4648
resolver_factory: compilation.resolver_factory.clone(),
4749
loader_resolver_factory: compilation.loader_resolver_factory.clone(),
4850
old_cache: compilation.old_cache.clone(),
@@ -67,6 +69,7 @@ impl TaskContext {
6769
let mut compilation = Compilation::new(
6870
self.compiler_id,
6971
self.compiler_options.clone(),
72+
self.platform.clone(),
7073
self.plugin_driver.clone(),
7174
self.buildtime_plugin_driver.clone(),
7275
self.resolver_factory.clone(),

crates/rspack_core/src/compilation/mod.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ use crate::{
4545
ChunkByUkey, ChunkContentHash, ChunkGraph, ChunkGroupByUkey, ChunkGroupUkey, ChunkHashesArtifact,
4646
ChunkKind, ChunkNamedIdArtifact, ChunkRenderArtifact, ChunkRenderCacheArtifact,
4747
ChunkRenderResult, ChunkUkey, CodeGenerationJob, CodeGenerationResult, CodeGenerationResults,
48-
CompilationLogger, CompilationLogging, CompilerOptions, ConcatenationScope,
48+
CompilationLogger, CompilationLogging, CompilerOptions, CompilerPlatform, ConcatenationScope,
4949
DependenciesDiagnosticsArtifact, DependencyCodeGeneration, DependencyTemplate,
5050
DependencyTemplateType, DependencyType, DerefOption, Entry, EntryData, EntryOptions,
5151
EntryRuntime, Entrypoint, ExecuteModuleId, Filename, ImportPhase, ImportVarMap,
@@ -218,6 +218,7 @@ pub struct Compilation {
218218
pub hot_index: u32,
219219
pub records: Option<CompilationRecords>,
220220
pub options: Arc<CompilerOptions>,
221+
pub platform: Arc<CompilerPlatform>,
221222
pub entries: Entry,
222223
pub global_entry: EntryData,
223224
// module graph partial used in seal phase
@@ -337,6 +338,7 @@ impl Compilation {
337338
pub fn new(
338339
compiler_id: CompilerId,
339340
options: Arc<CompilerOptions>,
341+
platform: Arc<CompilerPlatform>,
340342
plugin_driver: SharedPluginDriver,
341343
buildtime_plugin_driver: SharedPluginDriver,
342344
resolver_factory: Arc<ResolverFactory>,
@@ -360,6 +362,7 @@ impl Compilation {
360362
runtime_template: RuntimeTemplate::new(options.clone()),
361363
records,
362364
options: options.clone(),
365+
platform,
363366
seal_module_graph_partial: None,
364367
dependency_factories: Default::default(),
365368
dependency_templates: Default::default(),

crates/rspack_core/src/compiler/mod.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ use tracing::instrument;
1414

1515
pub use self::rebuild::CompilationRecords;
1616
use crate::{
17-
BoxPlugin, CleanOptions, Compilation, CompilationAsset, CompilerOptions, ContextModuleFactory,
18-
Filename, KeepPattern, Logger, NormalModuleFactory, PluginDriver, ResolverFactory,
19-
SharedPluginDriver,
17+
BoxPlugin, CleanOptions, Compilation, CompilationAsset, CompilerOptions, CompilerPlatform,
18+
ContextModuleFactory, Filename, KeepPattern, Logger, NormalModuleFactory, PluginDriver,
19+
ResolverFactory, SharedPluginDriver,
2020
cache::{Cache, new_cache},
2121
compilation::build_module_graph::ModuleExecutor,
2222
fast_set, include_hash,
@@ -92,6 +92,7 @@ pub struct Compiler {
9292
/// emitted asset versions
9393
/// the key of HashMap is filename, the value of HashMap is version
9494
pub emitted_asset_versions: HashMap<String, String>,
95+
pub platform: Arc<CompilerPlatform>,
9596
compiler_context: Arc<CompilerContext>,
9697
}
9798

@@ -110,6 +111,7 @@ impl Compiler {
110111
resolver_factory: Option<Arc<ResolverFactory>>,
111112
loader_resolver_factory: Option<Arc<ResolverFactory>>,
112113
compiler_context: Option<Arc<CompilerContext>>,
114+
platform: Arc<CompilerPlatform>,
113115
) -> Self {
114116
#[cfg(debug_assertions)]
115117
{
@@ -162,6 +164,7 @@ impl Compiler {
162164
compilation: Compilation::new(
163165
id,
164166
options,
167+
platform.clone(),
165168
plugin_driver.clone(),
166169
buildtime_plugin_driver.clone(),
167170
resolver_factory.clone(),
@@ -188,6 +191,7 @@ impl Compiler {
188191
old_cache,
189192
emitted_asset_versions: Default::default(),
190193
input_filesystem,
194+
platform,
191195
compiler_context,
192196
}
193197
}
@@ -219,6 +223,7 @@ impl Compiler {
219223
Compilation::new(
220224
self.id,
221225
self.options.clone(),
226+
self.platform.clone(),
222227
self.plugin_driver.clone(),
223228
self.buildtime_plugin_driver.clone(),
224229
self.resolver_factory.clone(),

0 commit comments

Comments
 (0)