Files
Donny/강동윤andGitHub 8007df067f feat: emit ECMA-426 source map scopes behind experimental flag (#11582)
## Summary

Implements ECMA-426 source map scope emission behind a new opt-in flag:

- Adds `jsc.experimental.emitSourceMapScopes` (default `false`)
- Emits `scopes` metadata in output source maps when enabled
- Includes both original scope trees and generated range trees
- Includes variable lists and generated range bindings (`G`)
- Keeps behavior unchanged unless explicitly enabled

## What changed

### Config and API wiring

- Added `emit_source_map_scopes` to SWC config/build pipeline
- Added `emit_source_map_scopes` to compiler-base `PrintArgs`
- Added `emitSourceMapScopes?: boolean` to `packages/types`

### Codegen scope collection

- Extended `WriteJs` with scope hooks:
  - `start_scope`
  - `end_scope`
  - `add_scope_variable`
- Added forwarding in wrappers (`Box<W>`, `&mut W`, omit-trailing-semi
writer)
- Added scope model (`ScopeKind`, `BindingStorage`, `ScopeRecord`,
`ScopeBindingRecord`)
- Implemented collection in `JsWriter` with:
  - nested scope stack tracking
  - hoisted vs lexical placement
  - per-scope variable dedup by name

### Emitter instrumentation

- Instrumented module/script roots, function-like scopes, block scopes,
and catch scopes
- Collected bindings for params, var/let/const declarations,
function/class declarations
- Added helper module for pattern/parameter binding extraction

### Source map integration

- Added `SourceMapGenConfig::for_each_additional_name` hook
- Pre-registers additional scope-related names before mappings are
encoded
- Added scope encoder in compiler-base (`source_map_scopes.rs`) to
encode ECMA-426 tags (`B/C/D/E/F/G`)
- `scopes` is only emitted when:
  - source maps are enabled
  - `emitSourceMapScopes` is enabled
  - no input sourcemap composition (`orig.is_none()`)

## Tests

Added/updated tests for:

- codegen writer scope collection and wrapper forwarding
- compiler-base scope encoder behavior
- compiler-base print integration (enabled/disabled/orig composition)
- swc e2e source-map test for this issue
(`issue_11424_emit_source_map_scopes_opt_in`)

## Verification run

- `git submodule update --init --recursive`
- `cargo fmt --all`
- `cargo clippy --all --all-targets -- -D warnings`
- `cargo test -p swc_ecma_codegen`
- `cargo test -p swc_compiler_base`
- `cargo test -p swc_sourcemap`
- `cargo test -p swc`

Note: `cargo test -p swc` still has pre-existing environment-dependent
failures in `tests/source_map.rs` where Node cannot resolve
`sourcemap-validator` in this environment. The new
`issue_11424_emit_source_map_scopes_opt_in` test passes.

Fixes #11424
2026-02-25 12:25:42 -08:00

114 lines
3.5 KiB
Rust

use rustc_hash::FxHashMap;
use serde_json::Value;
use swc_common::{sync::Lrc, FileName, FilePathMapping, SourceMap};
use swc_compiler_base::{print, IdentCollector, PrintArgs, SourceMapsConfig};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_codegen::Config as CodegenConfig;
use swc_ecma_parser::{lexer::Lexer, EsSyntax, Parser, Syntax};
use swc_ecma_visit::VisitWith;
fn parse_program(cm: Lrc<SourceMap>, src: &str) -> Program {
let fm = cm.new_source_file(FileName::Real("input.js".into()).into(), src.to_owned());
let lexer = Lexer::new(
Syntax::Es(EsSyntax::default()),
EsVersion::Es2022,
(&*fm).into(),
None,
);
let mut parser = Parser::new_from(lexer);
Program::Module(parser.parse_module().expect("module should parse"))
}
fn print_map(
emit_source_map_scopes: bool,
orig: Option<swc_sourcemap::SourceMap>,
) -> (Value, swc_sourcemap::SourceMap) {
let cm: Lrc<SourceMap> = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let program = parse_program(cm.clone(), "function foo(a){let b=a;return b}");
let mut names = IdentCollector {
names: FxHashMap::default(),
};
program.visit_with(&mut names);
let output = print(
cm,
&program,
PrintArgs {
source_file_name: Some("input.js"),
inline_sources_content: true,
source_map: SourceMapsConfig::Bool(true),
source_map_names: &names.names,
orig,
emit_source_map_scopes,
codegen_config: CodegenConfig::default().with_target(EsVersion::Es2022),
..Default::default()
},
)
.expect("print should succeed");
let map_text = output.map.expect("source map should be emitted");
let map = swc_sourcemap::SourceMap::from_slice(map_text.as_bytes()).expect("valid source map");
let map_json: Value = serde_json::from_str(&map_text).expect("valid source map json");
(map_json, map)
}
#[test]
fn emits_scopes_when_enabled() {
let (map_json, map) = print_map(true, None);
assert!(map_json.get("scopes").and_then(|v| v.as_str()).is_some());
assert!(map.get_scopes().is_some());
}
#[test]
fn registers_scope_related_names_when_enabled() {
let (map_json, _map) = print_map(true, None);
let names = map_json
.get("names")
.and_then(|v| v.as_array())
.expect("names array should exist")
.iter()
.filter_map(|v| v.as_str())
.collect::<Vec<_>>();
assert!(names.contains(&"module"));
assert!(names.contains(&"function"));
}
#[test]
fn scopes_round_trip_matches_json_field() {
let (map_json, map) = print_map(true, None);
let from_json = map_json
.get("scopes")
.and_then(|v| v.as_str())
.expect("scopes should exist in json");
let from_map = map
.get_scopes()
.expect("scopes should exist in decoded map");
assert_eq!(from_json, from_map);
}
#[test]
fn skips_scopes_when_disabled() {
let (map_json, map) = print_map(false, None);
assert!(map_json.get("scopes").is_none());
assert!(map.get_scopes().is_none());
}
#[test]
fn skips_scopes_when_composing_from_orig() {
let orig = swc_sourcemap::SourceMap::from_slice(
br#"{
"version": 3,
"sources": ["input.js"],
"names": [],
"mappings": "AAAA"
}"#,
)
.expect("valid input source map");
let (map_json, map) = print_map(true, Some(orig));
assert!(map_json.get("scopes").is_none());
assert!(map.get_scopes().is_none());
}