Skip to content

Commit

Permalink
feat(semantic): support get node id by scope id
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing committed Dec 26, 2023
1 parent 0c81cf0 commit 457da1e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 6 additions & 0 deletions crates/oxc_semantic/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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
Expand Down
13 changes: 11 additions & 2 deletions crates/oxc_semantic/src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>>;

Expand All @@ -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>,
Expand Down Expand Up @@ -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()))
Expand All @@ -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);
}
Expand Down

0 comments on commit 457da1e

Please sign in to comment.