Skip to content

Instantly share code, notes, and snippets.

@aneury1
Last active May 7, 2025 03:56
Show Gist options
  • Save aneury1/8d179f5d525dd48e3ec0bf9d720f7755 to your computer and use it in GitHub Desktop.
Save aneury1/8d179f5d525dd48e3ec0bf9d720f7755 to your computer and use it in GitHub Desktop.
#from tree_sitter import Language, Parser
#pip install tree-sitter tree-sitter-cpp
# Load compiled C++ parser
#CPP_LANGUAGE = Language('./my-languages.so')
#parser = Parser()
#parser.set_language(CPP_LANGUAGE)
path="/home/neon/Documents/projects/myprojects/old-experiments/simplenotepad/simpleInventario/test.cpp"
import sys
import tree_sitter_cpp as tscpp # tree_sitter_cpp binary wheel
from tree_sitter import Language, Parser # tree_sitter python binding
# Load the C++ language grammar (make sure you have the 'tree-sitter-cpp' grammar installed)
#CPP_LANGUAGE = Language('tree-sitter-cpp.so', 'cpp') // Not working for now
CPP_LANGUAGE = Language(tscpp.language())
# Initialize the Tree-sitter parser with the C++ grammar
parser = Parser(CPP_LANGUAGE)
# Load your C++ file
with open(path, 'r') as f:
code = f.read()
code_bytes = code.encode()
tree = parser.parse(code_bytes)
root_node = tree.root_node
def get_code_segment(node):
return code_bytes[node.start_byte:node.end_byte].decode()
def extract_variables(node):
"""Extract local variable declarations inside a function body."""
if node.type == 'declaration':
type_node = node.child_by_field_name('type')
decl_node = node.child_by_field_name('declarator')
if type_node and decl_node:
var_type = get_code_segment(type_node)
var_name = get_code_segment(decl_node)
print(f" Variable: {var_name}, Type: {var_type}")
for child in node.children:
extract_variables(child)
def find_functions_and_locals(node):
if node.type == 'function_definition':
decl_node = node.child_by_field_name('declarator')
func_name = get_code_segment(decl_node)
print(f"Function: {func_name}")
body = node.child_by_field_name('body')
extract_variables(body)
for child in node.children:
find_functions_and_locals(child)
find_functions_and_locals(root_node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment