rspack_plugin_javascript 0.103.1

rspack javascript plugin
Documentation
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use std::num::NonZeroU32;

use swc_next_ecma_ast::{BindingIdentifier, IdentifierReference, ScopeId, SymbolId};
use swc_next_ecma_semantic::{ReferenceSpace, Semantic, SymbolFlags};

use super::{
  Atom, AtomRef, BindingState, ParsedJavaScriptAst, ScopeInfoDB, ScopeInfoId, SemanticScopeId,
  SymbolBinding,
};

/// Append-only registry of immutable semantic lookup data for all retained ASTs.
#[derive(Default)]
pub(crate) struct SemanticStore<'ast> {
  /// Per-AST lookup records, with the original module registered first.
  asts: Vec<AstSemantic<'ast>>,
  /// Total size of the disjoint symbol ranges reserved by registered ASTs.
  symbol_count: u32,
  /// Total size of the disjoint semantic-scope ranges reserved by registered ASTs.
  scope_count: u32,
}

/// Active semantic environment, separate from stored AST data and mutable bindings.
pub(crate) struct SemanticContext<'ast> {
  /// Index of the currently active AST in the semantic store.
  active_ast: usize,
  /// Cached active AST reference, avoiding a registry lookup per identifier.
  ast: Option<&'ast ParsedJavaScriptAst<'ast>>,
  /// Cached offset mapping active AST symbol indices into the binding-state array.
  symbol_start: u32,
  /// Cached offset mapping active AST scopes into the shared default-owner array.
  scope_start: u32,
  /// Saved caller (AST index, SWC scope) pairs for name lookup and context restoration.
  parents: Vec<(usize, ScopeId)>,
  /// Current SWC scope within the active AST, independent of the Rspack scope.
  pub(crate) scope: ScopeId,
}

impl Default for SemanticContext<'_> {
  /// Creates an inactive context, ready for the first AST to be registered.
  fn default() -> Self {
    Self {
      active_ast: 0,
      ast: None,
      symbol_start: 0,
      scope_start: 0,
      parents: Vec::new(),
      scope: ScopeId::ROOT,
    }
  }
}

/// Per-AST lookup data, immutable after registration and separate from mutable binding state.
struct AstSemantic<'ast> {
  /// Borrowed parsed AST and its existing SWC semantic analysis, without cloning either.
  ast: &'ast ParsedJavaScriptAst<'ast>,
  /// Start of this AST's disjoint binding-state range in `ScopeInfoDB::symbols`.
  symbol_start: u32,
  /// Start of this AST's disjoint scope range in `ScopeInfoDB::semantic_scope_owners`.
  scope_start: u32,
  /// SWC program scope activated when this AST is entered.
  root_scope: ScopeId,
}

/// Maps a symbol and its semantic declaration scope into the database-wide ranges.
fn symbol_binding(
  semantic: &Semantic<'_>,
  symbol_start: u32,
  scope_start: u32,
  symbol: SymbolId,
) -> SymbolBinding {
  SymbolBinding {
    index: NonZeroU32::new(symbol_start + symbol.index() as u32 + 1)
      .expect("semantic symbol indices start at one"),
    scope: SemanticScopeId(
      NonZeroU32::new(scope_start + semantic.scope_of_symbol(symbol).raw())
        .expect("semantic scope indices start at one"),
    ),
  }
}

/// Immutable lookup information only; mutable binding state must be read again after hooks.
#[derive(Clone, Copy)]
pub(crate) enum IdentifierResolution {
  Symbol(SymbolId),
  Name,
  Unresolved,
}

impl<'ast> SemanticStore<'ast> {
  /// Registers semantic lookup tables and reserves a disjoint range for this AST's symbols.
  fn register_ast(&mut self, ast: &'ast ParsedJavaScriptAst<'ast>) -> usize {
    let info = AstSemantic {
      ast,
      symbol_start: self.symbol_count,
      scope_start: self.scope_count,
      root_scope: ast
        .semantic
        .scope_of(ast.program.node_id())
        .expect("program has a semantic scope"),
    };
    let scope_count = ast.semantic.iter_scopes().count() as u32;
    self.scope_count = self
      .scope_count
      .checked_add(scope_count)
      .filter(|count| *count < u32::MAX - 1)
      .expect("too many semantic scopes");
    let mut symbol_count = 0;
    for entry in ast.semantic.iter_symbols() {
      symbol_count = symbol_count.max(entry.id.index() + 1);
    }
    let symbol_end = info
      .symbol_start
      .checked_add(u32::try_from(symbol_count).expect("too many semantic bindings"))
      .expect("too many semantic bindings");
    self.symbol_count = symbol_end;
    let index = self.asts.len();
    self.asts.push(info);
    index
  }

  /// Finds a value symbol in the active AST, then in saved fragment callers.
  #[inline(never)]
  pub(super) fn symbol_for_name(
    &self,
    context: &SemanticContext<'_>,
    name: &str,
  ) -> Option<SymbolBinding> {
    // These roots and the synthetic default export cannot name lexical bindings.
    // Their aliases and tags live in the Rspack overlay, also for replacement ASTs.
    if matches!(name, "this" | "import.meta" | "new.target" | "*default*") {
      return None;
    }
    let semantic = context.ast?.semantic;
    semantic
      .lookup(context.scope, name.as_bytes(), ReferenceSpace::Value)
      .map(|symbol| symbol_binding(semantic, context.symbol_start, context.scope_start, symbol))
      .or_else(|| {
        if context.parents.is_empty() {
          None
        } else {
          self.symbol_in_parent_ast(context, name)
        }
      })
  }

  /// Keeps fragment-only caller lookup out of the inlined ordinary-name path.
  #[cold]
  #[inline(never)]
  fn symbol_in_parent_ast(
    &self,
    context: &SemanticContext<'_>,
    name: &str,
  ) -> Option<SymbolBinding> {
    context.parents.iter().rev().find_map(|&(ast, scope)| {
      let info = &self.asts[ast];
      info
        .ast
        .semantic
        .lookup(scope, name.as_bytes(), ReferenceSpace::Value)
        .map(|symbol| {
          symbol_binding(
            info.ast.semantic,
            info.symbol_start,
            info.scope_start,
            symbol,
          )
        })
    })
  }
}

impl<'ast> SemanticContext<'ast> {
  /// Activates a fragment's root scope, saving its caller for lookup and restoration.
  fn enter_ast(&mut self, store: &SemanticStore<'ast>, index: usize) {
    self.parents.push((self.active_ast, self.scope));
    self.set_ast(store, index);
    self.scope = store.asts[index].root_scope;
  }

  /// Restores the caller's AST and semantic scope after processing a fragment.
  fn leave_ast(&mut self, store: &SemanticStore<'ast>) {
    let (index, scope) = self.parents.pop().expect("active fragment");
    self.set_ast(store, index);
    self.scope = scope;
  }

  /// Switches the active AST and refreshes the cached reference and symbol offset.
  fn set_ast(&mut self, store: &SemanticStore<'ast>, index: usize) {
    let info = &store.asts[index];
    self.active_ast = index;
    self.ast = Some(info.ast);
    self.symbol_start = info.symbol_start;
    self.scope_start = info.scope_start;
  }

  /// Classifies an identifier using semantic data without reading mutable binding state.
  #[inline]
  pub(crate) fn identifier_resolution(
    &self,
    parsed: &ParsedJavaScriptAst<'_>,
    identifier: IdentifierReference,
  ) -> IdentifierResolution {
    debug_assert!(self.ast.is_some_and(|ast| std::ptr::eq(ast, parsed)));
    let semantic = parsed.semantic;
    let Some(reference) = semantic.reference_of(identifier.node_id()) else {
      return IdentifierResolution::Name;
    };
    let reference = semantic.reference(reference);
    match reference.symbol {
      Some(symbol) => IdentifierResolution::Symbol(symbol),
      // A fragment is evaluated in its caller's environment, not as a separate module.
      None if !self.parents.is_empty() => IdentifierResolution::Name,
      None => IdentifierResolution::Unresolved,
    }
  }
}

impl<'ast> ScopeInfoDB<'ast> {
  /// Creates the module scope and initializes its bindings from the original AST's semantic data.
  pub fn with_semantic(ast: &'ast ParsedJavaScriptAst<'ast>) -> Self {
    let mut db = Self::new();
    let index = db.register_ast(ast);
    db.semantic_context.set_ast(&db.semantic, index);
    db.semantic_context.scope = db.semantic.asts[index].root_scope;
    db.create();
    db.initialize_scope_bindings();
    db
  }

  /// Registers an AST and allocates its initially unset binding-state slots.
  pub(crate) fn register_ast(&mut self, ast: &'ast ParsedJavaScriptAst<'ast>) -> usize {
    let index = self.semantic.register_ast(ast);
    self
      .symbols
      .resize(self.semantic.symbol_count as usize, None);
    self
      .semantic_scope_owners
      .resize(self.semantic.scope_count as usize, None);
    index
  }

  /// Activates a registered fragment and initializes its bindings in the current Rspack scope.
  pub(crate) fn enter_ast(&mut self, index: usize) {
    self.semantic_context.enter_ast(&self.semantic, index);
    self.initialize_scope_bindings();
  }

  /// Restores the caller's semantic context; Rspack scope exit handles binding rollback separately.
  pub(crate) fn leave_ast(&mut self) {
    self.semantic_context.leave_ast(&self.semantic);
  }

  /// Reads an override or derives the default state from the symbol's active semantic scope.
  #[inline]
  pub(super) fn symbol_state(&self, symbol: SymbolBinding) -> Option<BindingState> {
    self.symbols[symbol.index()]
      .or_else(|| self.semantic_scope_owners[symbol.scope.index()].map(BindingState::Normal))
  }

  /// Updates a symbol while preserving scope-exit restoration and persistent outer writes.
  pub(super) fn set_symbol(
    &mut self,
    symbol: SymbolBinding,
    state: BindingState,
    scope: ScopeInfoId,
  ) {
    let index = symbol.index();
    let previous = self.symbols[index];
    if self.current != Some(scope) {
      // Outer writes persist even when an inner alias has queued a restore.
      let mut restore = previous;
      let mut recorded = false;
      let mut changed_restore = false;
      for i in (0..self.overrides.len()).rev() {
        let (overridden, previous, owner) = self.overrides[i];
        if overridden != symbol {
          continue;
        }
        if owner == scope {
          recorded = true;
        } else if self.is_descendant_of(owner, scope) {
          restore = previous;
          self.overrides[i].1 = Some(state);
          changed_restore = true;
        }
      }
      if !changed_restore && self.symbol_state(symbol) == Some(state) {
        return;
      }
      if !recorded && self.expect_get_scope(scope).parent.is_some() {
        // Keep the ancestor's restore before its descendants' ranges, so both
        // scope exit and ancestor enumeration retain their stack ordering.
        let start = self.expect_get_scope(scope).overrides_start;
        self.overrides.insert(start, (symbol, restore, scope));
        let mut child = self.current_scope();
        while child != scope {
          let info = self.expect_get_mut_scope(child);
          info.overrides_start += 1;
          child = info.parent.expect("outer writes target an active ancestor");
        }
      }
    } else {
      if self.symbol_state(symbol) == Some(state) {
        return;
      }
      if self.expect_get_scope(scope).parent.is_some() {
        self.overrides.push((symbol, previous, scope));
      }
    }
    self.symbols[index] = Some(state);
  }

  /// Resolves a name through semantic symbols, falling back to the name-based overlay.
  pub fn resolve<'key>(&mut self, name: impl Into<AtomRef<'key>>) -> Option<BindingState> {
    self.resolve_with_symbol(name).0
  }

  /// Keeps the immutable symbol lookup for an immediate read-modify-write operation.
  #[inline(always)]
  pub(crate) fn resolve_with_symbol<'key>(
    &mut self,
    name: impl Into<AtomRef<'key>>,
  ) -> (Option<BindingState>, Option<SymbolBinding>) {
    let name = name.into();
    let symbol = self
      .semantic
      .symbol_for_name(&self.semantic_context, name.as_str());
    if let Some(symbol) = symbol {
      if let Some(state) = self.symbol_state(symbol) {
        return (state.defined(), Some(symbol));
      }
      if let Some(state) = self.bind_existing_symbol(self.current_scope(), name, symbol) {
        return (state.defined(), Some(symbol));
      }
    }
    (self.get(self.current_scope(), name), symbol)
  }

  /// Reads the current binding state from a saved resolution, using name lookup when needed.
  #[inline(always)]
  pub(crate) fn resolve_identifier(
    &mut self,
    parsed: &ParsedJavaScriptAst<'_>,
    identifier: IdentifierReference,
    resolution: IdentifierResolution,
  ) -> Option<BindingState> {
    let ast = parsed.ast;
    if let IdentifierResolution::Name = resolution {
      return self.resolve_identifier_fallback(parsed, identifier, resolution);
    }
    if let IdentifierResolution::Symbol(symbol) = resolution {
      let index = self.semantic_context.symbol_start as usize + symbol.index();
      if let Some(state) = self.symbols[index] {
        return state.defined();
      }
      let scope = self.semantic_context.scope_start as usize
        + parsed.semantic.scope_of_symbol(symbol).raw() as usize
        - 1;
      if let Some(owner) = self.semantic_scope_owners[scope] {
        return Some(BindingState::Normal(owner));
      }
      return self.resolve_identifier_fallback(parsed, identifier, resolution);
    }
    self.get(self.current_scope(), ast.get_utf8(identifier.name(ast)))
  }

  /// Shares dynamic-name and inactive-symbol handling instead of inlining it at every use.
  #[cold]
  #[inline(never)]
  fn resolve_identifier_fallback(
    &mut self,
    parsed: &ParsedJavaScriptAst<'_>,
    identifier: IdentifierReference,
    resolution: IdentifierResolution,
  ) -> Option<BindingState> {
    let ast = parsed.ast;
    let name = ast.get_utf8(identifier.name(ast));
    if let IdentifierResolution::Name = resolution {
      return self.resolve(name);
    }
    if let IdentifierResolution::Symbol(symbol) = resolution {
      let symbol = symbol_binding(
        parsed.semantic,
        self.semantic_context.symbol_start,
        self.semantic_context.scope_start,
        symbol,
      );
      if let Some(state) = self.bind_existing_symbol(self.current_scope(), name, symbol) {
        return state.defined();
      }
      // Replacement trees and legacy scope mappings can still introduce a
      // binding through the name-based overlay.
    }
    self.get(self.current_scope(), name)
  }

  /// Reuses a declaration's semantic symbol while still observing mutable tags and aliases.
  pub(crate) fn resolve_binding(
    &mut self,
    parsed: &ParsedJavaScriptAst<'_>,
    identifier: BindingIdentifier,
  ) -> (Option<BindingState>, Option<SymbolBinding>) {
    debug_assert!(
      self
        .semantic_context
        .ast
        .is_some_and(|ast| std::ptr::eq(ast, parsed))
    );
    if let Some(symbol) = parsed.semantic.symbol_of(identifier.node_id()) {
      let symbol = symbol_binding(
        parsed.semantic,
        self.semantic_context.symbol_start,
        self.semantic_context.scope_start,
        symbol,
      );
      if let Some(state) = self.symbol_state(symbol) {
        return (state.defined(), Some(symbol));
      }
    }
    // Pre-walked block declarations may not have an active semantic owner yet.
    self.resolve_with_symbol(parsed.ast.get_utf8(identifier.name(parsed.ast)))
  }

  /// Defines a normal binding in the current scope without replacing its existing plugin tags.
  pub fn define(&mut self, name: Atom) {
    let scope = self.current_scope();
    if let Some(state) = self.resolve(&name) {
      let info = self.expect_get_variable(state);
      if info.tag_info.is_some() && info.declared_scope == scope {
        return;
      }
    }
    self.set(scope, name, BindingState::Normal(scope));
  }

  /// Activates shared default owners for the current scope.
  pub fn initialize_scope_bindings(&mut self) {
    let scope = self.current_scope();
    let id = SemanticScopeId::from_index(
      self.semantic_context.scope_start as usize + self.semantic_context.scope.raw() as usize - 1,
    );
    if self.semantic_scope_owners[id.index()].is_none() {
      self.semantic_scope_owners[id.index()] = Some(scope);
      self.scope_activations.push(id);
    }
  }

  /// Hides callback parameter bindings to preserve require.ensure's free-name handling.
  pub fn suppress_scope_parameters(&mut self) {
    let parsed = self.semantic_context.ast.expect("active AST");
    let scope = self.current_scope();
    for symbol in parsed.semantic.bindings(self.semantic_context.scope) {
      if parsed
        .semantic
        .symbol(symbol)
        .flags
        .contains(SymbolFlags::PARAMETER)
      {
        let index = symbol_binding(
          parsed.semantic,
          self.semantic_context.symbol_start,
          self.semantic_context.scope_start,
          symbol,
        );
        self.set_symbol(index, BindingState::Tombstone, scope);
      }
    }
  }

  /// Collects current-scope variables from the name overlay and semantic bindings.
  pub fn current_variables(&self) -> Vec<(Atom, BindingState)> {
    let scope = self.current_scope();
    let mut variables = self
      .scope_variable_bindings(scope)
      .filter_map(|(name, _, visible)| visible.defined().map(|state| (name.clone(), state)))
      .collect::<Vec<_>>();
    let Some(info) = self.semantic.asts.get(self.semantic_context.active_ast) else {
      return variables;
    };
    let parsed = info.ast;
    for symbol in parsed.semantic.bindings(self.semantic_context.scope) {
      if !parsed
        .semantic
        .symbol(symbol)
        .flags
        .visible_in(ReferenceSpace::Value)
      {
        continue;
      }
      let Some(state) = self
        .symbol_state(symbol_binding(
          parsed.semantic,
          info.symbol_start,
          info.scope_start,
          symbol,
        ))
        .and_then(BindingState::defined)
      else {
        continue;
      };
      if self.expect_get_variable(state).declared_scope != scope {
        continue;
      }
      let name = parsed.semantic.symbol(symbol).name;
      let name = parsed.ast.get_wtf8(name).to_string_lossy();
      // The overlay has already supplied visible metadata for names it owns,
      // including tombstones and persistent ancestor writes.
      if self.get_raw(scope, name.as_ref()).is_none() {
        variables.push((Atom::from(name.as_ref()), state));
      }
    }
    variables
  }
}