feat(semantic): support get node id by scope id (#1826)

This is useful when we want to get the ast node that corresponds to the current scope.
This commit is contained in:
Dunqing 2023-12-27 22:30:28 +08:00 committed by GitHub
parent ea8a59b6bc
commit f7b7f0a512
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 2 deletions

View file

@ -415,10 +415,12 @@ impl<'a> SemanticBuilder<'a> {
AstKind::Function(func) => {
self.function_stack.push(self.current_node_id);
func.bind(self);
self.add_node_id();
self.make_all_namespaces_valuelike();
}
AstKind::ArrowExpression(_) => {
self.function_stack.push(self.current_node_id);
self.add_node_id();
self.make_all_namespaces_valuelike();
}
AstKind::Class(class) => {
@ -537,6 +539,10 @@ impl<'a> SemanticBuilder<'a> {
}
}
fn add_node_id(&mut self) {
self.scope.add_node_id(self.current_scope_id, self.current_node_id);
}
fn make_all_namespaces_valuelike(&mut self) {
for symbol_id in &self.namespace_stack {
// Ambient modules cannot be value modules

View file

@ -7,7 +7,7 @@ use oxc_span::Atom;
pub use oxc_syntax::scope::{ScopeFlags, ScopeId};
use rustc_hash::{FxHashMap, FxHasher};
use crate::{reference::ReferenceId, symbol::SymbolId};
use crate::{reference::ReferenceId, symbol::SymbolId, AstNodeId};
type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
@ -24,7 +24,8 @@ pub struct ScopeTree {
/// Maps a scope to direct children scopes
child_ids: FxHashMap<ScopeId, Vec<ScopeId>>,
// Maps a scope to its node id
node_ids: FxHashMap<ScopeId, AstNodeId>,
flags: IndexVec<ScopeId, ScopeFlags>,
bindings: IndexVec<ScopeId, Bindings>,
unresolved_references: IndexVec<ScopeId, UnresolvedReferences>,
@ -111,6 +112,10 @@ impl ScopeTree {
&self.bindings[scope_id]
}
pub fn get_node_id(&self, scope_id: ScopeId) -> Option<&AstNodeId> {
self.node_ids.get(&scope_id)
}
pub fn iter_bindings(&self) -> impl Iterator<Item = (ScopeId, SymbolId, Atom)> + '_ {
self.bindings.iter_enumerated().flat_map(|(scope_id, bindings)| {
bindings.iter().map(move |(name, symbol_id)| (scope_id, *symbol_id, name.clone()))
@ -134,6 +139,10 @@ impl ScopeTree {
scope_id
}
pub(crate) fn add_node_id(&mut self, scope_id: ScopeId, node_id: AstNodeId) {
self.node_ids.insert(scope_id, node_id);
}
pub fn add_binding(&mut self, scope_id: ScopeId, name: Atom, symbol_id: SymbolId) {
self.bindings[scope_id].insert(name, symbol_id);
}