From c96e739b96442439e18ef58f506347b2f1688cf2 Mon Sep 17 00:00:00 2001 From: Dunqing <29533304+Dunqing@users.noreply.github.com> Date: Wed, 23 Oct 2024 15:50:09 +0000 Subject: [PATCH] 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 --- crates/oxc_traverse/src/context/mod.rs | 39 ++++++++++++++++++++------ 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/crates/oxc_traverse/src/context/mod.rs b/crates/oxc_traverse/src/context/mod.rs index 8bb4e82276bc5..63fd5b548a9d9 100644 --- a/crates/oxc_traverse/src/context/mod.rs +++ b/crates/oxc_traverse/src/context/mod.rs @@ -301,6 +301,36 @@ impl<'a> TraverseCtx<'a> { 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. /// /// 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> { // Get name for UID let name = self.generate_uid_name(name); - 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) + self.generate_binding(name, scope_id, flags) } /// Generate UID in current scope.