This document explains how to work with local variables in Codegen.
Overview
Through the CodeBlock class, Graph-sitter exposes APIs for analyzing and manipulating local variables within code blocks.
Basic Usage
Every code block (function body, loop body, etc.) provides access to its local variables:
# Get all local variables in a function
function = codebase.get_function("process_data")
local_vars = function.code_block.local_var_assignments
for var in local_vars:
print(var.name)
# Find a specific variable
config_var = function.code_block.get_local_var_assignment("config")
config_var.rename("settings") # Updates all references safely
# Rename a variable used in this scope (but not necessarily declared here)
function.rename_local_variable("foo", "bar")
Fuzzy Matching
Graph-sitter supports fuzzy matching when searching for local variables. This allows you to find variables whose names contain a substring, rather than requiring exact matches:
# Get all local variables containing "config"
function = codebase.get_function("process_data")
# Exact match - only finds variables named exactly "config"
exact_matches = function.code_block.get_local_var_assignments("config")
# Returns: config = {...}
# Fuzzy match - finds any variable containing "config"
fuzzy_matches = function.code_block.get_local_var_assignments("config", fuzzy_match=True)
# Returns: config = {...}, app_config = {...}, config_settings = {...}
# Fuzzy matching also works for variable usages
usages = function.code_block.get_variable_usages("config", fuzzy_match=True)
# And for renaming variables
function.code_block.rename_variable_usages("config", "settings", fuzzy_match=True)
# Renames: config -> settings, app_config -> app_settings, config_settings -> settings_settings
Be careful with fuzzy matching when renaming variables, as it will replace the
matched substring in all variable names. This might lead to unintended renames
like config_settings
becoming settings_settings
.