feat(traverse): add generate_binding and generate_binding_current_scope APIs in context (#6805)

These two APIs are used to create a symbol with the provided symbol name, The difference from `generate_uid` is that we don't need to create a unique name for the symbol.

If you have a better method name for this, Feel free to edit this PR directly
This commit is contained in:
Dunqing 2024-10-23 15:50:09 +00:00
parent 22355f73f3
commit c96e739b96

View file

@ -301,6 +301,36 @@ impl<'a> TraverseCtx<'a> {
self.scoping.remove_scope_for_expression(scope_id, expr); self.scoping.remove_scope_for_expression(scope_id, expr);
} }
/// Generate binding.
///
/// Creates a symbol with the provided name and flags and adds it to the specified scope.
pub fn generate_binding(
&mut self,
name: CompactStr,
scope_id: ScopeId,
flags: SymbolFlags,
) -> BoundIdentifier<'a> {
let name_atom = self.ast.atom(&name);
// Add binding to scope
let symbol_id =
self.symbols_mut().create_symbol(SPAN, name.clone(), flags, scope_id, NodeId::DUMMY);
self.scopes_mut().add_binding(scope_id, name, symbol_id);
BoundIdentifier::new(name_atom, symbol_id)
}
/// Generate binding in current scope.
///
/// Creates a symbol with the provided name and flags and adds it to the current scope.
pub fn generate_in_current_scope(
&mut self,
name: CompactStr,
flags: SymbolFlags,
) -> BoundIdentifier<'a> {
self.generate_binding(name, self.current_scope_id(), flags)
}
/// Generate UID var name. /// Generate UID var name.
/// ///
/// Finds a unique variable name which does clash with any other variables used in the program. /// Finds a unique variable name which does clash with any other variables used in the program.
@ -326,14 +356,7 @@ impl<'a> TraverseCtx<'a> {
) -> BoundIdentifier<'a> { ) -> BoundIdentifier<'a> {
// Get name for UID // Get name for UID
let name = self.generate_uid_name(name); let name = self.generate_uid_name(name);
let name_atom = self.ast.atom(&name); self.generate_binding(name, scope_id, flags)
// Add binding to scope
let symbol_id =
self.symbols_mut().create_symbol(SPAN, name.clone(), flags, scope_id, NodeId::DUMMY);
self.scopes_mut().add_binding(scope_id, name, symbol_id);
BoundIdentifier::new(name_atom, symbol_id)
} }
/// Generate UID in current scope. /// Generate UID in current scope.