-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextract_function_info.py
More file actions
executable file
·1598 lines (1355 loc) · 67.6 KB
/
extract_function_info.py
File metadata and controls
executable file
·1598 lines (1355 loc) · 67.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Function Information Extraction Pipeline
This script extracts comprehensive function information from Python game repositories
including signatures, bodies, metadata, and structural analysis for future processing.
"""
import ast
import os
import sys
import json
import hashlib
import subprocess
from typing import Dict, List, Any, Optional, Tuple, Union
from dataclasses import dataclass, asdict
from pathlib import Path
from datetime import datetime
import argparse
from tqdm import tqdm
try:
from tree_sitter import Language, Parser
import tree_sitter_cpp
import tree_sitter_c
TREE_SITTER_AVAILABLE = True
except ImportError:
TREE_SITTER_AVAILABLE = False
@dataclass
class FunctionInfo:
"""Container for extracted function information"""
name: str
signature: str
body: str
docstring: Optional[str]
line_start: int
line_end: int
column_offset: int
parameters: List[Dict[str, Any]]
return_annotation: Optional[str]
decorators: List[str]
is_async: bool
is_method: bool
is_static_method: bool
is_class_method: bool
complexity_score: int
calls_made: List[str]
variables_used: List[str]
control_structures: List[str]
imports_used: List[str]
@dataclass
class ClassInfo:
"""Container for class information"""
name: str
line_start: int
line_end: int
docstring: Optional[str]
base_classes: List[str]
methods: List[str]
class_variables: List[str]
decorators: List[str]
@dataclass
class FileInfo:
"""Container for complete file analysis"""
file_path: str
relative_path: str
repository: str
file_size: int
line_count: int
file_hash: str
encoding: str
imports: List[Dict[str, str]]
global_variables: List[Dict[str, Any]]
functions: List[FunctionInfo]
classes: List[ClassInfo]
main_execution_block: Optional[str]
complexity_metrics: Dict[str, Any]
ast_valid: bool
extraction_timestamp: str
class FunctionExtractor:
"""Advanced function and code structure extractor"""
def __init__(self, base_directory: str = "repos_GAME_python_demo", min_lines: int = 28):
"""Initialize the extractor"""
self.base_directory = Path(base_directory)
self.python_extensions = {'.py'}
self.ts_extensions = {'.ts', '.tsx', '.js', '.jsx'}
self.cpp_extensions = {'.cpp', '.cc', '.cxx', '.hpp'} # .h is handled with heuristic
self.c_extensions = {'.c'}
self.excluded_files = {'__pycache__', '.git', '.gitignore', 'requirements.txt', 'setup.py'}
self.excluded_dirs = {'__pycache__', '.git', '.github', 'node_modules', 'venv', 'env'}
self.min_lines = min_lines
self.ts_extractor_script = Path(__file__).parent / "extract_ts_info.js"
self.failed_files = [] # Track failed files
self.cpp_parser = None
self.c_parser = None
if TREE_SITTER_AVAILABLE:
try:
self.cpp_language = Language(tree_sitter_cpp.language())
self.cpp_parser = Parser(self.cpp_language)
self.c_language = Language(tree_sitter_c.language())
self.c_parser = Parser(self.c_language)
except Exception as e:
print(f"Failed to initialize tree-sitter: {e}")
def safe_unparse(self, node: ast.AST) -> str:
"""Safely unparse AST node"""
try:
if hasattr(ast, 'unparse'):
return ast.unparse(node)
else:
# Fallback for older Python versions
import astor
return astor.to_source(node).strip()
except:
return 'complex_expression'
def calculate_complexity_score(self, node: ast.AST) -> int:
"""Calculate cyclomatic complexity of a function"""
complexity = 1 # Base complexity
for child in ast.walk(node):
# Decision points that increase complexity
if isinstance(child, (ast.If, ast.While, ast.For, ast.AsyncFor)):
complexity += 1
elif isinstance(child, ast.ExceptHandler):
complexity += 1
elif isinstance(child, (ast.And, ast.Or)):
complexity += 1
elif isinstance(child, ast.comprehension):
complexity += 1
return complexity
def extract_function_calls(self, node: ast.AST) -> List[str]:
"""Extract function calls made within a function"""
calls = []
for child in ast.walk(node):
if isinstance(child, ast.Call):
if isinstance(child.func, ast.Name):
calls.append(child.func.id)
elif isinstance(child.func, ast.Attribute):
# Handle method calls like obj.method()
if isinstance(child.func.value, ast.Name):
calls.append(f"{child.func.value.id}.{child.func.attr}")
else:
calls.append(child.func.attr)
return list(set(calls)) # Remove duplicates
def extract_variables_used(self, node: ast.AST) -> List[str]:
"""Extract variables referenced in a function"""
variables = []
for child in ast.walk(node):
if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Load):
variables.append(child.id)
return list(set(variables))
def extract_control_structures(self, node: ast.AST) -> List[str]:
"""Extract control flow structures used"""
structures = []
for child in ast.walk(node):
if isinstance(child, ast.If):
structures.append('if')
elif isinstance(child, ast.While):
structures.append('while')
elif isinstance(child, ast.For):
structures.append('for')
elif isinstance(child, ast.Try):
structures.append('try')
elif isinstance(child, ast.With):
structures.append('with')
elif isinstance(child, ast.AsyncFor):
structures.append('async_for')
elif isinstance(child, ast.AsyncWith):
structures.append('async_with')
return list(set(structures))
def extract_function_parameters(self, func_node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> List[Dict[str, Any]]:
"""Extract detailed parameter information"""
parameters = []
# Regular arguments
for i, arg in enumerate(func_node.args.args):
param_info = {
'name': arg.arg,
'type_annotation': self.safe_unparse(arg.annotation) if arg.annotation else None,
'position': i,
'kind': 'positional',
'default': None
}
# Check for default values
defaults_offset = len(func_node.args.args) - len(func_node.args.defaults)
if i >= defaults_offset:
default_idx = i - defaults_offset
param_info['default'] = self.safe_unparse(func_node.args.defaults[default_idx])
parameters.append(param_info)
# *args parameter
if func_node.args.vararg:
parameters.append({
'name': func_node.args.vararg.arg,
'type_annotation': self.safe_unparse(func_node.args.vararg.annotation) if func_node.args.vararg.annotation else None,
'position': len(parameters),
'kind': 'var_positional',
'default': None
})
# Keyword-only arguments
for i, arg in enumerate(func_node.args.kwonlyargs):
param_info = {
'name': arg.arg,
'type_annotation': self.safe_unparse(arg.annotation) if arg.annotation else None,
'position': len(parameters),
'kind': 'keyword_only',
'default': None
}
# Check for keyword defaults
if i < len(func_node.args.kw_defaults) and func_node.args.kw_defaults[i]:
param_info['default'] = self.safe_unparse(func_node.args.kw_defaults[i])
parameters.append(param_info)
# **kwargs parameter
if func_node.args.kwarg:
parameters.append({
'name': func_node.args.kwarg.arg,
'type_annotation': self.safe_unparse(func_node.args.kwarg.annotation) if func_node.args.kwarg.annotation else None,
'position': len(parameters),
'kind': 'var_keyword',
'default': None
})
return parameters
def extract_decorators(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> List[str]:
"""Extract decorator information"""
decorators = []
for decorator in node.decorator_list:
try:
decorators.append(self.safe_unparse(decorator))
except:
# Fallback for complex decorators
if isinstance(decorator, ast.Name):
decorators.append(decorator.id)
else:
decorators.append('complex_decorator')
return decorators
def is_method_type(self, func_node: Union[ast.FunctionDef, ast.AsyncFunctionDef], class_context: bool = False) -> Tuple[bool, bool, bool]:
"""Determine if function is method, static method, or class method"""
is_method = class_context
is_static = False
is_class = False
if class_context:
decorators = self.extract_decorators(func_node)
is_static = any('staticmethod' in dec for dec in decorators)
is_class = any('classmethod' in dec for dec in decorators)
return is_method, is_static, is_class
def extract_function_info(self, func_node: Union[ast.FunctionDef, ast.AsyncFunctionDef], source_lines: List[str],
class_context: bool = False) -> FunctionInfo:
"""Extract comprehensive information about a function"""
# Basic information
name = func_node.name
line_start = func_node.lineno
line_end = getattr(func_node, 'end_lineno', line_start)
column_offset = func_node.col_offset
# Extract function body
body_lines = source_lines[line_start-1:line_end]
body = '\n'.join(body_lines)
# Generate signature
try:
# Create a simple signature representation
params = []
for arg in func_node.args.args:
param_str = arg.arg
if arg.annotation:
param_str += f": {self.safe_unparse(arg.annotation)}"
params.append(param_str)
if func_node.args.vararg:
param_str = f"*{func_node.args.vararg.arg}"
if func_node.args.vararg.annotation:
param_str += f": {self.safe_unparse(func_node.args.vararg.annotation)}"
params.append(param_str)
if func_node.args.kwarg:
param_str = f"**{func_node.args.kwarg.arg}"
if func_node.args.kwarg.annotation:
param_str += f": {self.safe_unparse(func_node.args.kwarg.annotation)}"
params.append(param_str)
signature = f"def {name}({', '.join(params)})"
if func_node.returns:
signature += f" -> {self.safe_unparse(func_node.returns)}"
except:
signature = f"def {name}(...)" # Fallback
# Extract detailed information
parameters = self.extract_function_parameters(func_node)
decorators = self.extract_decorators(func_node)
is_method, is_static_method, is_class_method = self.is_method_type(func_node, class_context)
return FunctionInfo(
name=name,
signature=signature,
body=body,
docstring=ast.get_docstring(func_node),
line_start=line_start,
line_end=line_end,
column_offset=column_offset,
parameters=parameters,
return_annotation=self.safe_unparse(func_node.returns) if func_node.returns else None,
decorators=decorators,
is_async=isinstance(func_node, ast.AsyncFunctionDef),
is_method=is_method,
is_static_method=is_static_method,
is_class_method=is_class_method,
complexity_score=self.calculate_complexity_score(func_node),
calls_made=self.extract_function_calls(func_node),
variables_used=self.extract_variables_used(func_node),
control_structures=self.extract_control_structures(func_node),
imports_used=[] # Will be populated during file-level analysis
)
def extract_class_info(self, class_node: ast.ClassDef, source_lines: List[str]) -> ClassInfo:
"""Extract information about a class"""
return ClassInfo(
name=class_node.name,
line_start=class_node.lineno,
line_end=getattr(class_node, 'end_lineno', class_node.lineno),
docstring=ast.get_docstring(class_node),
base_classes=[self.safe_unparse(base) for base in class_node.bases],
methods=[node.name for node in class_node.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))],
class_variables=[node.targets[0].id for node in class_node.body
if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name)],
decorators=[self.safe_unparse(dec) for dec in class_node.decorator_list]
)
def extract_imports(self, tree: ast.AST) -> List[Dict[str, str]]:
"""Extract import information"""
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.append({
'type': 'import',
'module': alias.name,
'alias': alias.asname,
'line': node.lineno
})
elif isinstance(node, ast.ImportFrom):
module = node.module or ''
for alias in node.names:
imports.append({
'type': 'from_import',
'module': module,
'name': alias.name,
'alias': alias.asname,
'line': node.lineno,
'level': node.level
})
return imports
def extract_global_variables(self, tree: ast.AST) -> List[Dict[str, Any]]:
"""Extract global variable definitions"""
variables = []
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
variables.append({
'name': target.id,
'line': node.lineno,
'value': self.safe_unparse(node.value)
})
return variables
def extract_main_execution(self, tree: ast.AST, source_lines: List[str]) -> Optional[str]:
"""Extract main execution block (if __name__ == '__main__')"""
for node in tree.body:
if (isinstance(node, ast.If) and
isinstance(node.test, ast.Compare) and
isinstance(node.test.left, ast.Name) and
node.test.left.id == '__name__'):
# Extract the main block
start_line = node.lineno - 1
end_line = getattr(node, 'end_lineno', len(source_lines))
return '\n'.join(source_lines[start_line:end_line])
return None
def calculate_file_complexity(self, functions: List[FunctionInfo], classes: List[ClassInfo]) -> Dict[str, Any]:
"""Calculate overall file complexity metrics"""
if not functions:
return {
'total_functions': 0,
'total_classes': len(classes),
'avg_function_complexity': 0,
'max_function_complexity': 0,
'total_lines_of_code': 0
}
complexities = [f.complexity_score for f in functions]
return {
'total_functions': len(functions),
'total_classes': len(classes),
'avg_function_complexity': sum(complexities) / len(complexities),
'max_function_complexity': max(complexities),
'total_lines_of_code': sum(f.line_end - f.line_start + 1 for f in functions)
}
def is_function_body_long_enough(self, func_node: Union[ast.FunctionDef, ast.AsyncFunctionDef], min_lines: int = 28) -> bool:
"""Check if function body has enough lines of code (excluding docstring and decorators)"""
# Get line numbers safely
start_line = getattr(func_node, 'lineno', 0)
end_line = getattr(func_node, 'end_lineno', 0)
if not start_line or not end_line:
return False
# Calculate total lines
total_lines = end_line - start_line + 1
# Subtract docstring if present
docstring = ast.get_docstring(func_node)
if docstring:
# Docstring typically takes 3 lines (""" ... """)
total_lines = max(0, total_lines - 3)
# Subtract decorator lines
total_lines = max(0, total_lines - len(func_node.decorator_list))
# Subtract 1 for the function definition line
total_lines = max(0, total_lines - 1)
return total_lines >= min_lines
def analyze_python_file(self, file_path: Path) -> Optional[FileInfo]:
"""Analyze a single Python file and extract all information"""
try:
# Read file content
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
source_lines = content.splitlines()
# Calculate file metadata
file_size = file_path.stat().st_size
file_hash = hashlib.sha256(content.encode('utf-8')).hexdigest()
relative_path = str(file_path.relative_to(self.base_directory))
repository = relative_path.split('/')[0] if '/' in relative_path else "unknown"
# Parse AST
try:
tree = ast.parse(content)
ast_valid = True
except SyntaxError as e:
print(f"Syntax error in {file_path}: {e}")
self.failed_files.append({
'file_path': str(file_path),
'error': str(e),
'content': content
})
return None
# Extract functions and classes
functions = []
classes = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
# Skip functions with small bodies
if self.is_function_body_long_enough(node, self.min_lines):
func_info = self.extract_function_info(node, source_lines)
functions.append(func_info)
elif isinstance(node, ast.ClassDef):
class_info = self.extract_class_info(node, source_lines)
classes.append(class_info)
# Extract methods from class
for class_node in node.body:
if isinstance(class_node, (ast.FunctionDef, ast.AsyncFunctionDef)):
# Skip methods with small bodies
if self.is_function_body_long_enough(class_node, self.min_lines):
method_info = self.extract_function_info(class_node, source_lines, class_context=True)
functions.append(method_info)
# Skip files with no substantial functions
if not functions and not classes:
return None
# Extract other information
imports = self.extract_imports(tree)
global_variables = self.extract_global_variables(tree)
main_execution = self.extract_main_execution(tree, source_lines)
complexity_metrics = self.calculate_file_complexity(functions, classes)
# Link imports to functions (simplified approach)
import_names = {imp['module'] for imp in imports if imp['type'] == 'import'}
import_names.update({imp['name'] for imp in imports if imp['type'] == 'from_import'})
for func in functions:
func.imports_used = [imp for imp in import_names if any(imp in call for call in func.calls_made)]
return FileInfo(
file_path=str(file_path),
relative_path=relative_path,
repository=repository,
file_size=file_size,
line_count=len(source_lines),
file_hash=file_hash,
encoding='utf-8',
imports=imports,
global_variables=global_variables,
functions=functions,
classes=classes,
main_execution_block=main_execution,
complexity_metrics=complexity_metrics,
ast_valid=ast_valid,
extraction_timestamp=datetime.now().isoformat()
)
except Exception as e:
print(f"Error analyzing file {file_path}: {e}")
# Try to read content if possible, otherwise empty
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
except:
content = "Could not read content"
self.failed_files.append({
'file_path': str(file_path),
'error': str(e),
'content': content
})
return None
def analyze_cpp_file(self, file_path: Path) -> Optional[FileInfo]:
"""Analyze a single C++ file using tree-sitter"""
if not self.cpp_parser:
print(f"Skipping C++ file {file_path}: tree-sitter-cpp not initialized")
return None
try:
# Read file content
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
content_bytes = content.encode('utf-8')
# Use tree-sitter to parse
tree = self.cpp_parser.parse(content_bytes)
# Find functions and classes
functions = []
classes = []
cursor = tree.walk()
def traverse(node, class_context=False):
# Handle Functions
if node.type == 'function_definition' or node.type == 'template_declaration':
# If template, look inside for function_definition
target_node = node
if node.type == 'template_declaration':
# Find the underlying declaration
for child in node.children:
if child.type == 'function_definition':
target_node = child
break
else:
# Skip independent template declarations (like class templates, which are handled below)
pass
if target_node.type == 'function_definition':
func_info = self._extract_cpp_function_info(target_node, content, content_bytes, node if node.type == 'template_declaration' else None, class_context=class_context)
if self.is_function_body_long_enough_cpp(target_node):
functions.append(func_info)
# Don't return here! We might need to traverse children (e.g. lambdas, though typically not nested functions in C++)
# Actually, to be safe and avoid complexity, we can stop here for this branch unless we want detailed lambda support.
# But wait, C++ functions can't have nested functions (standard), but can have classes.
return
# Handle Classes/Structs
if node.type in ('class_specifier', 'struct_specifier'):
class_info = self._extract_cpp_class_info(node, content, content_bytes)
classes.append(class_info)
# Traverse children with class context
for child in node.children:
traverse(child, class_context=True)
return
# Traverse children
for child in node.children:
traverse(child, class_context)
traverse(tree.root_node)
# Metadata
file_size = file_path.stat().st_size
file_hash = hashlib.sha256(content_bytes).hexdigest()
line_count = len(content.splitlines())
relative_path = str(file_path.relative_to(self.base_directory))
repository = relative_path.split('/')[0] if '/' in relative_path else "unknown"
complexity_metrics = self.calculate_file_complexity(functions, classes)
return FileInfo(
file_path=str(file_path),
relative_path=relative_path,
repository=repository,
file_size=file_size,
line_count=line_count,
file_hash=file_hash,
encoding='utf-8',
imports=[], # Extraction of includes could be added
global_variables=[], # Extraction of globals could be added
functions=functions,
classes=classes,
main_execution_block=None,
complexity_metrics=complexity_metrics,
ast_valid=True,
extraction_timestamp=datetime.now().isoformat()
)
except Exception as e:
print(f"Error analyzing C++ file {file_path}: {e}")
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
except:
content = "Could not read content"
self.failed_files.append({
'file_path': str(file_path),
'error': str(e),
'content': content
})
return None
def analyze_c_file(self, file_path: Path) -> Optional[FileInfo]:
"""Analyze a single C file using tree-sitter-c"""
if not self.c_parser:
print(f"Skipping C file {file_path}: tree-sitter-c not initialized")
return None
try:
# Read file content
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
content_bytes = content.encode('utf-8')
tree = self.c_parser.parse(content_bytes)
functions = []
classes = [] # structs
cursor = tree.walk()
def traverse(node):
# Handle Functions
if node.type == 'function_definition':
func_info = self._extract_cpp_function_info(node, content, content_bytes, class_context=False)
if self.is_function_body_long_enough_cpp(node):
functions.append(func_info)
return
# Handle Structs / Unions
if node.type in ('struct_specifier', 'union_specifier'):
# Check if it is anonymous and wrapped in typedef
# Handled at 'type_definition' level usually, but we can capture named structs here
if node.child_by_field_name('name'):
class_info = self._extract_c_struct_info(node, content, content_bytes)
classes.append(class_info)
return
# Handle Typedef Structs
if node.type == 'type_definition':
# Check if subtype is struct_specifier
type_node = node.child_by_field_name('type')
declarator = node.child_by_field_name('declarator')
if type_node and type_node.type in ('struct_specifier', 'union_specifier'):
# It is a typedef struct
# We pass the type_definition name as the class name
name_str = "unknown"
if declarator and declarator.type == 'type_identifier':
name_str = content_bytes[declarator.start_byte:declarator.end_byte].decode('utf-8')
class_info = self._extract_c_struct_info(type_node, content, content_bytes, name_override=name_str)
classes.append(class_info)
return # Should we traverse children? struct body is inside type_node
for child in node.children:
traverse(child)
traverse(tree.root_node)
# Metadata
file_size = file_path.stat().st_size
file_hash = hashlib.sha256(content_bytes).hexdigest()
line_count = len(content.splitlines())
relative_path = str(file_path.relative_to(self.base_directory))
repository = relative_path.split('/')[0] if '/' in relative_path else "unknown"
complexity_metrics = self.calculate_file_complexity(functions, classes)
return FileInfo(
file_path=str(file_path),
relative_path=relative_path,
repository=repository,
file_size=file_size,
line_count=line_count,
file_hash=file_hash,
encoding='utf-8',
imports=[],
global_variables=[],
functions=functions,
classes=classes,
main_execution_block=None,
complexity_metrics=complexity_metrics,
ast_valid=True,
extraction_timestamp=datetime.now().isoformat()
)
except Exception as e:
print(f"Error analyzing C file {file_path}: {e}")
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
except:
content = "Could not read content"
self.failed_files.append({
'file_path': str(file_path),
'error': str(e),
'content': content
})
return None
def _extract_c_struct_info(self, node, content: str, content_bytes: bytes, name_override: str = None) -> ClassInfo:
start_point = node.start_point
end_point = node.end_point
name = name_override
if not name:
name_node = node.child_by_field_name('name')
if name_node:
name = content_bytes[name_node.start_byte:name_node.end_byte].decode('utf-8')
else:
name = "anonymous_struct"
docstring = None
prev = node.prev_sibling
if prev and prev.type == 'comment':
docstring = content_bytes[prev.start_byte:prev.end_byte].decode('utf-8')
methods = [] # function pointers
body_node = node.child_by_field_name('body')
if body_node:
for child in body_node.children:
if child.type == 'field_declaration':
# Check for function pointer
# field_declaration -> declarator: function_declarator or pointer_declarator wrapping function_declarator
declarator = child.child_by_field_name('declarator')
if self._is_function_pointer(declarator):
# Extract name
fp_name = self._extract_function_pointer_name(declarator, content_bytes)
if fp_name:
methods.append(fp_name)
return ClassInfo(
name=name,
line_start=start_point[0] + 1,
line_end=end_point[0] + 1,
docstring=docstring,
base_classes=[],
methods=methods,
class_variables=[],
decorators=[]
)
def _is_function_pointer(self, declarator_node) -> bool:
if not declarator_node: return False
# recursive check
curr = declarator_node
while curr:
if curr.type == 'function_declarator':
return True
if curr.type == 'parenthesized_declarator':
curr = curr.child_by_field_name('declarator')
continue
if curr.type == 'pointer_declarator':
curr = curr.child_by_field_name('declarator')
continue
break
return False
def _extract_function_pointer_name(self, declarator_node, content_bytes) -> Optional[str]:
# Drill down to identifier
curr = declarator_node
while curr:
if curr.type == 'identifier' or curr.type == 'field_identifier':
return content_bytes[curr.start_byte:curr.end_byte].decode('utf-8')
if curr.child_by_field_name('declarator'):
curr = curr.child_by_field_name('declarator')
elif curr.child_count > 0:
# fallback heuristic
for child in curr.children:
res = self._extract_function_pointer_name(child, content_bytes)
if res: return res
break
else:
break
return None
def _extract_cpp_function_name(self, node, content_bytes: bytes) -> str:
"""Helper to extract function name from node"""
declarator = node.child_by_field_name('declarator')
name = "unknown"
# Drill down declarator to find name
curr = declarator
while curr:
if curr.type == 'function_declarator':
declarator = curr.child_by_field_name('declarator')
curr = declarator
elif curr.type == 'identifier':
name = content_bytes[curr.start_byte:curr.end_byte].decode('utf-8')
break
elif curr.type == 'field_identifier':
name = content_bytes[curr.start_byte:curr.end_byte].decode('utf-8')
break
elif curr.type == 'qualified_identifier':
name = content_bytes[curr.start_byte:curr.end_byte].decode('utf-8')
break
elif curr.type == 'destructor_name':
name = content_bytes[curr.start_byte:curr.end_byte].decode('utf-8')
break
elif curr.type == 'reference_declarator' or curr.type == 'pointer_declarator':
curr = curr.child_by_field_name('declarator')
else:
if curr.child_count > 0:
found = False
for child in curr.children:
if child.type == 'identifier':
name = content_bytes[child.start_byte:child.end_byte].decode('utf-8')
found = True
break
if found: break
break
return name
def _extract_cpp_function_info(self, node, content: str, content_bytes: bytes, template_node=None, class_context: bool = False) -> FunctionInfo:
# Get basic info
start_byte = node.start_byte
end_byte = node.end_byte
start_point = node.start_point # (row, col)
end_point = node.end_point
# Use template node for full range if it exists
if template_node:
start_byte = template_node.start_byte
end_byte = template_node.end_byte
start_point = template_node.start_point
end_point = template_node.end_point
body_node = node.child_by_field_name('body')
body = content_bytes[start_byte:end_byte].decode('utf-8')
# Name
name = self._extract_cpp_function_name(node, content_bytes)
declarator = node.child_by_field_name('declarator')
parameters_node = None
# Extract parameters node (similar to name extraction path)
curr = declarator
if not parameters_node and declarator and declarator.type == 'function_declarator':
parameters_node = declarator.child_by_field_name('parameters')
# Signature (without body)
signature_end = body_node.start_byte if body_node else end_byte
signature = content_bytes[start_byte:signature_end].decode('utf-8').strip()
# Docstring (comments before)
docstring = None
# Look at previous sibling of the start node
prev = (template_node or node).prev_sibling
if prev and prev.type == 'comment':
docstring = content_bytes[prev.start_byte:prev.end_byte].decode('utf-8')
# Parameters
parameters = []
if parameters_node:
for i, param in enumerate(parameters_node.children):
if param.type in ('parameter_declaration', 'optional_parameter_declaration'):
p_name = "unknown"
p_type = "unknown"
# Extract type and name
p_type_node = param.child_by_field_name('type')
p_decl_node = param.child_by_field_name('declarator')
if p_type_node:
p_type = content_bytes[p_type_node.start_byte:p_type_node.end_byte].decode('utf-8')
if p_decl_node:
p_name = content_bytes[p_decl_node.start_byte:p_decl_node.end_byte].decode('utf-8')
parameters.append({
'name': p_name,
'type_annotation': p_type,
'position': i,
'kind': 'positional',
'default': None
})
# Return type
return_type = None
type_node = node.child_by_field_name('type')
if type_node:
return_type = content_bytes[type_node.start_byte:type_node.end_byte].decode('utf-8')
# Properties
is_static = False
# Check modifiers inside traversal or source text?
# Tree sitter structure for 'storage_class_specifier' usually sibling or child
# Actually in C++, static is part of storage_class_specifier in declaration
# For simplicity, check raw text of signature parts?
# Or check children of function_definition (it can have storage_class_specifier)
for child in node.children:
if child.type == 'storage_class_specifier' and 'static' in content_bytes[child.start_byte:child.end_byte].decode('utf-8'):
is_static = True
return FunctionInfo(
name=name,
signature=signature,
body=body,
docstring=docstring,
line_start=start_point[0] + 1,
line_end=end_point[0] + 1,
column_offset=start_point[1],
parameters=parameters,
return_annotation=return_type,
decorators=[], # decorators like [[nodiscard]] could be extracted
is_async=False, # C++ coroutines exist but simple check for now
is_method=class_context,
is_static_method=is_static,
is_class_method=False,
complexity_score=self._calculate_cpp_complexity(node),
calls_made=self._extract_cpp_calls(node, content_bytes),
variables_used=[],
control_structures=self._extract_cpp_control_structures(node),
imports_used=[]
)
def _extract_cpp_class_info(self, node, content: str, content_bytes: bytes) -> ClassInfo:
start_point = node.start_point
end_point = node.end_point
name_node = node.child_by_field_name('name')
name = "anonymous"