Codegen provides powerful capabilities for analyzing and visualizing function call relationships in your codebase. This guide will show you how to traverse the call graph and create visual representations of function call paths.
At the heart of call graph traversal is the .function_calls property, which returns information about all function calls made within a function:
Copy
Ask AI
def example_function(): result = helper_function() process_data() return result# Get all calls made by example_functionsuccessors = example_function.function_callsfor successor in successors: print(f"Call: {successor.source}") # The actual function call print(f"Called: {successor.function_definition.name}") # The function being called
You can filter the graph to show only relevant paths and visualize the results:
Copy
Ask AI
# Find all paths between start and endall_paths = nx.all_simple_paths(graph, source=start, target=end)# Create subgraph of only the nodes in these pathsnodes_in_paths = set()for path in all_paths: nodes_in_paths.update(path)filtered_graph = graph.subgraph(nodes_in_paths)# Visualize the graphcodebase.visualize(filtered_graph)
You can use call graph analysis to find unused functions:
Copy
Ask AI
def find_dead_code(codebase): dead_functions = [] for function in codebase.functions: if not any(function.function_calls): # No other functions call this one dead_functions.append(function) return dead_functions
def get_max_call_chain(function): G = nx.DiGraph() def build_graph(func, depth=0): if depth > 10: # Prevent infinite recursion return for call in func.function_calls: called_func = call.function_definition G.add_edge(func, called_func) build_graph(called_func, depth + 1) build_graph(function) return nx.dag_longest_path(G)
The .function_calls property is optimized for performance and uses Codegen’s internal graph structure to quickly traverse relationships. It’s much faster than parsing the code repeatedly.
When traversing call graphs, be mindful of:
Recursive calls that could create infinite loops
External module calls that might not be resolvable
Dynamic/runtime function calls that can’t be statically analyzed