11# this will count functions in the AST
2- def count_functions (ast ):
3- # import function definition from the parser's ast
4- from parser .ast import FunctionDefinition , Program
2+ from parser .ast import FunctionDefinition , Program , Node
3+ from utils .get_lexer import get_lexer_for_file
4+ import os
5+
6+ def count_functions (file_path ):
7+ """Count function definitions in a file.
8+
9+ Args:
10+ file_path (str): Path to the file to analyze
11+
12+ Returns:
13+ int: Number of function definitions found
14+ """
15+ # Get the appropriate lexer for the file
16+ Lexer = get_lexer_for_file (file_path )
17+ lexer = Lexer ()
18+
19+ # Read the file content
20+ with open (file_path , 'r' , encoding = 'utf-8' ) as f :
21+ code = f .read ()
22+
23+ # Tokenize the code
24+ tokens = lexer .tokenize (code )
25+
26+ # Parse the tokens into an AST
27+ from parser .parser import Parser
28+ parser = Parser (tokens )
29+ ast = parser .parse ()
530
631 if not isinstance (ast , Program ):
732 return 0
833
934 function_count = 0
1035
11- # recursive search for function definitions in the AST
1236 def search_node (node ):
1337 nonlocal function_count
1438
39+ # Check if this is a function definition
1540 if isinstance (node , FunctionDefinition ):
1641 function_count += 1
1742
18- # process child nodes if they exist
19- if hasattr (node , 'statements' ) and node . statements :
43+ # Process child nodes based on their type
44+ if isinstance (node , Program ) :
2045 for statement in node .statements :
2146 search_node (statement )
47+ elif isinstance (node , FunctionDefinition ):
48+ for statement in node .body :
49+ search_node (statement )
50+ elif hasattr (node , 'statements' ) and node .statements :
51+ for statement in node .statements :
52+ search_node (statement )
53+ elif hasattr (node , 'body' ) and node .body :
54+ for statement in node .body :
55+ search_node (statement )
2256
23- if hasattr (node , 'body' ) and node .body :
24- for body_statement in node .body :
25- search_node (body_statement )
26-
27- # for binary operation, check both sides
57+ # Handle binary operations
2858 if hasattr (node , 'left' ):
2959 search_node (node .left )
3060 if hasattr (node , 'right' ):
3161 search_node (node .right )
3262
33- # check the value part of an assignment
63+ # Handle assignments
3464 if hasattr (node , 'value' ):
3565 search_node (node .value )
3666
37- # check function call arguments
67+ # Handle function call arguments
3868 if hasattr (node , 'arguments' ) and node .arguments :
3969 for arg in node .arguments :
4070 search_node (arg )
4171
42- # start recursive search from the root Program node
72+ # Start recursive search from the root Program node
4373 search_node (ast )
4474
4575 return function_count
0 commit comments