-
-
Notifications
You must be signed in to change notification settings - Fork 559
/
lib.rs
264 lines (238 loc) · 7.58 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#![recursion_limit = "256"]
#![feature(let_chains)]
#![feature(try_blocks)]
#[macro_use]
extern crate napi_derive;
extern crate rspack_allocator;
use std::pin::Pin;
use std::sync::Mutex;
use compiler::{Compiler, CompilerState, CompilerStateGuard};
use napi::bindgen_prelude::*;
use rspack_binding_options::BuiltinPlugin;
use rspack_core::{Compilation, PluginExt};
use rspack_error::Diagnostic;
use rspack_fs_node::{AsyncNodeWritableFileSystem, ThreadsafeNodeFS};
mod compiler;
mod diagnostic;
mod panic;
mod plugins;
mod resolver_factory;
pub use diagnostic::*;
use plugins::*;
use resolver_factory::*;
use rspack_binding_options::*;
use rspack_binding_values::*;
use rspack_tracing::chrome::FlushGuard;
#[napi]
pub struct Rspack {
js_plugin: JsHooksAdapterPlugin,
compiler: Pin<Box<Compiler>>,
state: CompilerState,
}
#[napi]
impl Rspack {
#[napi(constructor)]
pub fn new(
env: Env,
options: RawOptions,
builtin_plugins: Vec<BuiltinPlugin>,
register_js_taps: RegisterJsTaps,
output_filesystem: ThreadsafeNodeFS,
mut resolver_factory_reference: Reference<JsResolverFactory>,
) -> Result<Self> {
tracing::info!("raw_options: {:#?}", &options);
let mut plugins = Vec::new();
let js_plugin = JsHooksAdapterPlugin::from_js_hooks(env, register_js_taps)?;
plugins.push(js_plugin.clone().boxed());
for bp in builtin_plugins {
bp.append_to(env, &mut plugins)
.map_err(|e| Error::from_reason(format!("{e}")))?;
}
let compiler_options: rspack_core::CompilerOptions = options
.try_into()
.map_err(|e| Error::from_reason(format!("{e}")))?;
tracing::info!("normalized_options: {:#?}", &compiler_options);
let resolver_factory =
(*resolver_factory_reference).get_resolver_factory(compiler_options.resolve.clone());
let loader_resolver_factory = (*resolver_factory_reference)
.get_loader_resolver_factory(compiler_options.resolve_loader.clone());
let rspack = rspack_core::Compiler::new(
compiler_options,
plugins,
rspack_binding_options::buildtime_plugins::buildtime_plugins(),
Some(Box::new(
AsyncNodeWritableFileSystem::new(output_filesystem)
.map_err(|e| Error::from_reason(format!("Failed to create writable filesystem: {e}",)))?,
)),
None,
Some(resolver_factory),
Some(loader_resolver_factory),
);
Ok(Self {
compiler: Box::pin(Compiler::from(rspack)),
state: CompilerState::init(),
js_plugin,
})
}
#[napi]
pub fn set_non_skippable_registers(&self, kinds: Vec<RegisterJsTapKind>) {
self.js_plugin.set_non_skippable_registers(kinds)
}
/// Build with the given option passed to the constructor
#[napi(ts_args_type = "callback: (err: null | Error) => void")]
pub fn build(&mut self, env: Env, reference: Reference<Rspack>, f: JsFunction) -> Result<()> {
unsafe {
self.run(env, reference, |compiler, _guard| {
callbackify(env, f, async move {
compiler.build().await.map_err(|e| {
Error::new(
napi::Status::GenericFailure,
print_error_diagnostic(e, compiler.options.stats.colors),
)
})?;
tracing::info!("build ok");
drop(_guard);
Ok(())
})
})
}
}
/// Rebuild with the given option passed to the constructor
#[napi(
ts_args_type = "changed_files: string[], removed_files: string[], callback: (err: null | Error) => void"
)]
pub fn rebuild(
&mut self,
env: Env,
reference: Reference<Rspack>,
changed_files: Vec<String>,
removed_files: Vec<String>,
f: JsFunction,
) -> Result<()> {
use std::collections::HashSet;
unsafe {
self.run(env, reference, |compiler, _guard| {
callbackify(env, f, async move {
compiler
.rebuild(
HashSet::from_iter(changed_files.into_iter()),
HashSet::from_iter(removed_files.into_iter()),
)
.await
.map_err(|e| {
Error::new(
napi::Status::GenericFailure,
print_error_diagnostic(e, compiler.options.stats.colors),
)
})?;
tracing::info!("rebuild ok");
drop(_guard);
Ok(())
})
})
}
}
}
impl Rspack {
/// Run the given function with the compiler.
///
/// ## Safety
/// 1. The caller must ensure that the `Compiler` is not moved or dropped during the lifetime of the callback.
/// 2. `CompilerStateGuard` should and only be dropped so soon as each `Compiler` is free of use.
/// Accessing `Compiler` beyond the lifetime of `CompilerStateGuard` would lead to potential race condition.
unsafe fn run<R>(
&mut self,
env: Env,
reference: Reference<Rspack>,
f: impl FnOnce(&'static mut Compiler, CompilerStateGuard) -> Result<R>,
) -> Result<R> {
if self.state.running() {
return Err(concurrent_compiler_error());
}
let _guard = self.state.enter();
let mut compiler = reference.share_with(env, |s| {
// SAFETY: The mutable reference to `Compiler` is exclusive. It's guaranteed by the running state guard.
Ok(unsafe { s.compiler.as_mut().get_unchecked_mut() })
})?;
self.cleanup_last_compilation(&compiler.compilation);
// SAFETY:
// 1. `Compiler` is pinned and stored on the heap.
// 2. `JsReference` (NAPI internal mechanism) keeps `Compiler` alive until its instance getting garbage collected.
f(
unsafe { std::mem::transmute::<&mut Compiler, &'static mut Compiler>(*compiler) },
_guard,
)
}
fn cleanup_last_compilation(&self, compilation: &Compilation) {
JsCompilationWrapper::cleanup_last_compilation(compilation.id());
}
}
fn concurrent_compiler_error() -> Error {
Error::new(
napi::Status::GenericFailure,
"ConcurrentCompilationError: You ran rspack twice. Each instance only supports a single concurrent compilation at a time.",
)
}
#[derive(Default)]
enum TraceState {
On(Option<FlushGuard>),
#[default]
Off,
}
#[ctor]
fn init() {
panic::install_panic_handler();
}
fn print_error_diagnostic(e: rspack_error::Error, colored: bool) -> String {
Diagnostic::from(e)
.render_report(colored)
.expect("should print diagnostics")
}
static GLOBAL_TRACE_STATE: Mutex<TraceState> = Mutex::new(TraceState::Off);
/**
* Some code is modified based on
* https://github.com/swc-project/swc/blob/d1d0607158ab40463d1b123fed52cc526eba8385/bindings/binding_core_node/src/util.rs#L29-L58
* Apache-2.0 licensed
* Author Donny/강동윤
* Copyright (c)
*/
#[napi]
pub fn register_global_trace(
filter: String,
#[napi(ts_arg_type = "\"chrome\" | \"logger\"| \"console\"")] layer: String,
output: String,
) {
let mut state = GLOBAL_TRACE_STATE
.lock()
.expect("Failed to lock GLOBAL_TRACE_STATE");
if matches!(&*state, TraceState::Off) {
let guard = match layer.as_str() {
"chrome" => rspack_tracing::enable_tracing_by_env_with_chrome_layer(&filter, &output),
"console" => {
rspack_tracing::enable_tracing_by_env_with_tokio_console();
None
}
"logger" => {
rspack_tracing::enable_tracing_by_env(&filter, &output);
None
}
_ => panic!("not supported layer type:{layer}"),
};
let new_state = TraceState::On(guard);
*state = new_state;
}
}
#[napi]
pub fn cleanup_global_trace() {
let mut state = GLOBAL_TRACE_STATE
.lock()
.expect("Failed to lock GLOBAL_TRACE_STATE");
if let TraceState::On(guard) = &mut *state
&& let Some(g) = guard.take()
{
g.flush();
drop(g);
let new_state = TraceState::Off;
*state = new_state;
}
}