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,
};
#[derive(Default)]
pub(crate) struct SemanticStore<'ast> {
asts: Vec<AstSemantic<'ast>>,
symbol_count: u32,
scope_count: u32,
}
pub(crate) struct SemanticContext<'ast> {
active_ast: usize,
ast: Option<&'ast ParsedJavaScriptAst<'ast>>,
symbol_start: u32,
scope_start: u32,
parents: Vec<(usize, ScopeId)>,
pub(crate) scope: ScopeId,
}
impl Default for SemanticContext<'_> {
fn default() -> Self {
Self {
active_ast: 0,
ast: None,
symbol_start: 0,
scope_start: 0,
parents: Vec::new(),
scope: ScopeId::ROOT,
}
}
}
struct AstSemantic<'ast> {
ast: &'ast ParsedJavaScriptAst<'ast>,
symbol_start: u32,
scope_start: u32,
root_scope: ScopeId,
}
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"),
),
}
}
#[derive(Clone, Copy)]
pub(crate) enum IdentifierResolution {
Symbol(SymbolId),
Name,
Unresolved,
}
impl<'ast> SemanticStore<'ast> {
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
}
#[inline(never)]
pub(super) fn symbol_for_name(
&self,
context: &SemanticContext<'_>,
name: &str,
) -> Option<SymbolBinding> {
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)
}
})
}
#[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> {
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;
}
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;
}
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;
}
#[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),
None if !self.parents.is_empty() => IdentifierResolution::Name,
None => IdentifierResolution::Unresolved,
}
}
}
impl<'ast> ScopeInfoDB<'ast> {
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
}
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
}
pub(crate) fn enter_ast(&mut self, index: usize) {
self.semantic_context.enter_ast(&self.semantic, index);
self.initialize_scope_bindings();
}
pub(crate) fn leave_ast(&mut self) {
self.semantic_context.leave_ast(&self.semantic);
}
#[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))
}
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) {
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() {
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);
}
pub fn resolve<'key>(&mut self, name: impl Into<AtomRef<'key>>) -> Option<BindingState> {
self.resolve_with_symbol(name).0
}
#[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)
}
#[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)))
}
#[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();
}
}
self.get(self.current_scope(), name)
}
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));
}
}
self.resolve_with_symbol(parsed.ast.get_utf8(identifier.name(parsed.ast)))
}
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));
}
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);
}
}
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);
}
}
}
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();
if self.get_raw(scope, name.as_ref()).is_none() {
variables.push((Atom::from(name.as_ref()), state));
}
}
variables
}
}