Skip to content

Instantly share code, notes, and snippets.

@aneury1
Last active April 25, 2025 19:11
Show Gist options
  • Save aneury1/c6bf9bf7c6f57f569481574f4f9eabe2 to your computer and use it in GitHub Desktop.
Save aneury1/c6bf9bf7c6f57f569481574f4f9eabe2 to your computer and use it in GitHub Desktop.
import os
import clang.cindex
# install deps sudo apt install libclang-dev
# pip install clang
# Set path to libclang.so if neededimport os
import os
import clang.cindex
clang.cindex.Config.set_library_file('/usr/lib/llvm-15/lib/libclang.so') # adjust path if needed
def is_local_var(cursor, filename):
return (
cursor.kind == clang.cindex.CursorKind.VAR_DECL and
cursor.semantic_parent.kind == clang.cindex.CursorKind.FUNCTION_DECL and
cursor.location.file and os.path.samefile(cursor.location.file.name, filename)
)
def collect_vars_to_rename(cursor, filename):
to_rename = {}
def visit(node):
if is_local_var(node, filename):
name = node.spelling
if name.startswith('_'):
to_rename[name] = []
for child in node.get_children():
visit(child)
visit(cursor)
return to_rename
def collect_usages(cursor, filename, var_names, result):
if cursor.spelling in var_names and cursor.location.file and os.path.samefile(cursor.location.file.name, filename):
result[cursor.spelling].append((cursor.location.line, cursor.location.column, len(cursor.spelling)))
for child in cursor.get_children():
collect_usages(child, filename, var_names, result)
def rename_in_file(filepath):
index = clang.cindex.Index.create()
tu = index.parse(filepath, args=['-std=c++17'])
vars_to_rename = collect_vars_to_rename(tu.cursor, filepath)
if not vars_to_rename:
return
collect_usages(tu.cursor, filepath, vars_to_rename.keys(), vars_to_rename)
with open(filepath, 'r') as f:
lines = f.readlines()
# Flatten and sort all changes by file position (reverse order)
all_changes = []
for old_name, uses in vars_to_rename.items():
new_name = old_name.lstrip('_')
for (line, col, length) in uses:
all_changes.append((line, col, length, new_name))
for line, col, length, new_name in sorted(all_changes, reverse=True):
l = lines[line - 1]
lines[line - 1] = l[:col - 1] + new_name + l[col - 1 + length:]
with open(filepath, 'w') as f:
f.writelines(lines)
print(f"Renamed in {filepath}:", [k for k in vars_to_rename.keys()])
def process_folder(folder_path):
for root, _, files in os.walk(folder_path):
for file in files:
if file.endswith(('.cpp', '.c', '.hpp', '.h')):
full_path = os.path.join(root, file)
rename_in_file(full_path)
# Example usage
process_folder('./') # Replace with your folder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment