-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext-creator.py
More file actions
1594 lines (1431 loc) · 61.7 KB
/
Copy pathcontext-creator.py
File metadata and controls
1594 lines (1431 loc) · 61.7 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
import os
import sys
import argparse
import re
import json
import ctypes
from pathlib import Path
from tree_sitter import Language, Parser
# Ensure tree-sitter is available
try:
from tree_sitter import Language, Parser
except ImportError:
print("Error: tree_sitter library not found. Please install it using 'pip install tree-sitter'.")
sys.exit(1)
# Language pack support
try:
from tree_sitter_language_pack import get_language, get_parser, available_languages, download_all, cache_dir
HAS_LANGUAGE_PACK = True
except ImportError:
HAS_LANGUAGE_PACK = False
# Map of language names to their common file extensions
LANGUAGE_EXTENSIONS = {
# Systems programming
'c': ['.c', '.h'],
'cpp': ['.cpp', '.cxx', '.cc', '.c++', '.hpp', '.hxx', '.hh', '.ipp'],
'rust': ['.rs'],
'zig': ['.zig'],
'crystal': ['.cr'],
# General purpose
'python': ['.py', '.pyw', '.pyi'],
'javascript': ['.js', '.mjs', '.cjs', '.jsx'],
'typescript': ['.ts', '.mts', '.cts', '.tsx'],
'java': ['.java'],
'c_sharp': ['.cs'],
'go': ['.go'],
'ruby': ['.rb'],
'php': ['.php', '.phtml', '.php3', '.php4', '.php5'],
'perl': ['.pl', '.pm', '.t'],
'lua': ['.lua'],
'r': ['.r', '.R'],
'dart': ['.dart'],
'swift': ['.swift'],
'kotlin': ['.kt', '.kts', '.ktm'],
'scala': ['.scala', '.sc'],
'groovy': ['.groovy', '.gvy', '.gy', '.gsh'],
'haskell': ['.hs', '.lhs'],
'ocaml': ['.ml', '.mli'],
'elixir': ['.ex', '.exs'],
'erlang': ['.erl', '.hrl', '.escript'],
'clojure': ['.clj', '.cljs', '.cljc', '.edn'],
'fsharp': ['.fs', '.fsi', '.fsx'],
'julia': ['.jl'],
'd': ['.d', '.di'],
'v': ['.v'],
'nim': ['.nim', '.nims'],
'odin': ['.odin'],
# Web & markup
'html': ['.html', '.htm'],
'css': ['.css', '.scss', '.sass', '.less'],
'json': ['.json', '.jsonc'],
'yaml': ['.yaml', '.yml'],
'xml': ['.xml', '.xsd', '.xslt'],
'markdown': ['.md', '.markdown'],
'latex': ['.tex', '.sty', '.cls'],
'toml': ['.toml'],
# Scripting & config
'bash': ['.sh', '.bash', '.zsh', '.fish'],
'powershell': ['.ps1', '.psm1', '.psd1'],
'dockerfile': ['Dockerfile', 'docker-compose.yml'],
'cmake': ['.cmake', 'CMakeLists.txt'],
'make': ['Makefile', 'GNUmakefile'],
'sql': ['.sql'],
# Mobile
'objc': ['.m', '.mm'],
# Data & query
'graphql': ['.graphql', '.gql'],
'regex': ['.regex'],
# Infrastructure
'terraform': ['.tf', '.tfvars'],
'nix': ['.nix'],
}
PARSERS = {}
LANGUAGES = {}
def detect_languages_in_project(root: Path) -> set:
"""Scan project to detect which languages are actually present. (Feature 10)"""
detected = set()
ext_to_lang = {}
for lang, exts in LANGUAGE_EXTENSIONS.items():
for ext in exts:
ext_to_lang[ext.lower()] = lang
for r, dirs, files in os.walk(root):
dirs[:] = [d for d in dirs if d not in ['.git', 'node_modules', 'venv', '.venv', '__pycache__', '.next', 'dist', 'build', 'target']]
for f in files:
fp = Path(r) / f
lang = ext_to_lang.get(fp.suffix.lower())
if lang:
detected.add(lang)
# Check filename-based matches
for lgn, fnames in LANGUAGE_EXTENSIONS.items():
if f in fnames:
detected.add(lgn)
return detected
def build_parsers(target_languages=None, project_root=None):
"""Build parsers - lazy loading based on project detection. (Feature 10)"""
global PARSERS, LANGUAGES
if not HAS_LANGUAGE_PACK:
print("Error: tree-sitter-language-pack is required.")
sys.exit(1)
# Ensure languages are downloaded
try:
langs = available_languages()
if not langs:
print("Downloading language models (one-time)...")
download_all()
langs = available_languages()
except Exception as e:
print(f"Warning: Could not check available languages: {e}")
return
# Determine which languages to load
if target_languages:
# User specified filter
languages_to_load = set(target_languages) & set(langs)
elif project_root:
# Auto-detect from project (Feature 10: lazy loading)
languages_to_load = detect_languages_in_project(project_root) & set(langs)
if languages_to_load:
print(f"Auto-detected languages: {', '.join(sorted(languages_to_load))}")
else:
# Load all
languages_to_load = set(langs)
if not languages_to_load:
print("Warning: No languages detected or specified.")
return
print(f"Loading {len(languages_to_load)} language parser(s)...")
loaded = 0
lib_dir = Path(cache_dir())
for lang_name in sorted(languages_to_load):
try:
# Manually load language from the pack's compiled libraries to ensure
# compatibility with the tree-sitter Python package (0.22.0+)
lib_name = f"libtree_sitter_{lang_name}.so"
if sys.platform == "darwin":
lib_name = f"libtree_sitter_{lang_name}.dylib"
elif sys.platform == "win32":
lib_name = f"tree_sitter_{lang_name}.dll"
lib_path = lib_dir / lib_name
if not lib_path.exists():
# Fallback to get_parser/get_language if manual load fails
parser = get_parser(lang_name)
language = get_language(lang_name)
else:
lib = ctypes.cdll.LoadLibrary(str(lib_path))
symbol_name = f"tree_sitter_{lang_name}"
func = getattr(lib, symbol_name)
func.restype = ctypes.c_void_p
language = Language(func())
parser = Parser(language)
PARSERS[lang_name] = parser
LANGUAGES[lang_name] = language
loaded += 1
except Exception as e:
pass # Skip silently
print(f"✓ Loaded {loaded} parser(s)")
def get_parser_for_file(file_path: Path):
"""Get the appropriate parser for a file based on its extension."""
filename = file_path.name
ext = file_path.suffix.lower()
for lang_name, extensions in LANGUAGE_EXTENSIONS.items():
if filename in extensions and lang_name in PARSERS:
return PARSERS[lang_name], lang_name, LANGUAGES[lang_name]
for lang_name, extensions in LANGUAGE_EXTENSIONS.items():
if ext in extensions and lang_name in PARSERS:
return PARSERS[lang_name], lang_name, LANGUAGES[lang_name]
if HAS_LANGUAGE_PACK:
try:
from tree_sitter_language_pack import detect_language_from_path
detected_lang = detect_language_from_path(str(file_path))
if detected_lang and detected_lang in PARSERS:
return PARSERS[detected_lang], detected_lang, LANGUAGES[detected_lang]
except:
pass
return None, None, None
def get_node_text(node) -> str:
return node.text.decode('utf8', errors='ignore').strip()
def find_nodes(node, target_types):
"""Find all nodes of specific types in the AST."""
if isinstance(target_types, str):
target_types = [target_types]
results = []
if node.type in target_types:
results.append(node)
for child in node.children:
results.extend(find_nodes(child, target_types))
return results
# ============================================================
# Feature 3, 4, 5: Enhanced symbol extraction helpers
# ============================================================
def extract_byte_range(node) -> dict:
"""Extract byte and line range from a node. (Feature 3)"""
return {
'startByte': node.start_byte,
'endByte': node.end_byte,
'startLine': node.start_point[0],
'endLine': node.end_point[0],
'startColumn': node.start_point[1],
'endColumn': node.end_point[1],
}
def extract_signature(node, content: bytes) -> str:
"""Extract the first line (signature) of a symbol. (Feature 4)"""
text = content[node.start_byte:node.end_byte].decode('utf8', errors='ignore')
first_line = text.split('\n')[0].strip()
return first_line[:200] # Cap length
def extract_docstring(node, lang: str) -> str | None:
"""Extract docstring from a symbol node. (Feature 5)"""
if lang == 'python':
# Python: first string literal in body
body = None
for child in node.children:
if child.type == 'block':
body = child
break
if body:
for child in body.children:
if child.type in ('string', 'string_literal'):
text = get_node_text(child).strip()
if text.startswith(('"""', "'''", '"', "'")) and len(text) > 4:
return text.strip('\'"')
elif lang in ('javascript', 'typescript'):
# JS/TS: JSDoc comment is a 'comment' node before the declaration
prev = node.prev_named_sibling
if prev and prev.type == 'comment':
text = get_node_text(prev)
if text.startswith('/**'):
return text
# Also check first string in body
for child in node.children:
if child.type == 'statement_block':
for gc in child.children:
if gc.type in ('string', 'string_literal'):
text = get_node_text(gc).strip()
if text.startswith(('`', '"', "'")) and len(text) > 4:
return text
break
elif lang == 'java':
# Java: comment before method
prev = node.prev_named_sibling
if prev and prev.type == 'line_comment':
return get_node_text(prev)
if prev and prev.type == 'block_comment':
return get_node_text(prev)
elif lang == 'go':
# Go: comment before func
prev = node.prev_named_sibling
if prev and prev.type == 'comment':
return get_node_text(prev)
elif lang == 'rust':
# Rust: doc comment (/// or /** */)
prev = node.prev_named_sibling
if prev and prev.type == 'line_comment':
text = get_node_text(prev)
if text.startswith('///') or text.startswith('//!'):
return text
return None
def extract_comments_in_body(node, lang: str, content: bytes) -> list:
"""Extract TODO, FIXME, HACK comments from symbol body. (Feature 5)"""
comments = []
body_text = content[node.start_byte:node.end_byte].decode('utf8', errors='ignore')
lines = body_text.split('\n')
markers = ['TODO', 'FIXME', 'HACK', 'XXX', 'BUG', 'NOTE']
for i, line in enumerate(lines):
line_stripped = line.strip()
if any(m in line_stripped for m in markers):
# Extract the comment portion
for m in markers:
if m in line_stripped:
idx = line_stripped.index(m)
comments.append({
'line': node.start_point[0] + i + 1,
'marker': m,
'text': line_stripped[idx:idx+120]
})
break
return comments
def extract_parameters(node, lang: str) -> list:
"""Extract parameter info from function node. (Feature 4)"""
params = []
if lang == 'python':
for child in node.children:
if child.type == 'parameters':
for param in child.children:
if param.type == 'identifier':
name = get_node_text(param)
if name not in ('self', 'cls'):
params.append({'name': name, 'type': None})
elif param.type == 'typed_parameter':
for gc in param.children:
if gc.type == 'identifier':
pname = get_node_text(gc)
elif gc.type in ('type', 'type_identifier'):
ptype = get_node_text(gc)
if pname not in ('self', 'cls'):
params.append({'name': pname, 'type': ptype if 'ptype' in dir() else None})
break
elif lang in ('javascript', 'typescript'):
for child in node.children:
if child.type == 'formal_parameters':
for param in child.children:
if param.type == 'identifier':
params.append({'name': get_node_text(param), 'type': None})
elif param.type == 'assignment_pattern':
for gc in param.children:
if gc.type == 'identifier':
params.append({'name': get_node_text(gc), 'type': None})
break
break
elif lang == 'go':
for child in node.children:
if child.type == 'parameter_list':
for param in child.children:
if param.type == 'parameter_declaration':
names = [get_node_text(gc) for gc in param.children if gc.type == 'identifier']
type_nodes = [get_node_text(gc) for gc in param.children if gc.type in ('type_identifier', 'slice_type', 'pointer_type')]
ptype = type_nodes[0] if type_nodes else None
for n in names:
params.append({'name': n, 'type': ptype})
break
elif lang in ('java', 'c_sharp', 'cpp', 'c'):
for child in node.children:
if child.type == 'formal_parameters':
for param in child.children:
if param.type in ('formal_parameter', 'parameter_declaration'):
pname = None
ptype = None
for gc in param.children:
if gc.type == 'identifier':
pname = get_node_text(gc)
elif gc.type in ('type_identifier', 'primitive_type', 'array_type', 'scoped_type_identifier'):
ptype = get_node_text(gc)
if pname:
params.append({'name': pname, 'type': ptype})
break
return params
def extract_return_type(node, lang: str) -> str | None:
"""Extract return type from function signature. (Feature 4)"""
if lang == 'python':
for child in node.children:
if child.type == 'type':
return get_node_text(child)
elif lang in ('javascript', 'typescript'):
for child in node.children:
if child.type == 'return_type':
return get_node_text(child)
elif lang == 'go':
for child in node.children:
if child.type == 'result':
return get_node_text(child)
elif lang in ('java', 'c_sharp', 'c', 'cpp'):
# Return type is typically the first type child before function name
for child in node.children:
if child.type in ('type_identifier', 'primitive_type', 'void_type'):
return get_node_text(child)
if child.type == 'identifier':
break # Past the return type
return None
def extract_modifiers(node, lang: str) -> list:
"""Extract modifiers like async, static, public, etc. (Feature 4)"""
modifiers = []
if lang in ('javascript', 'typescript'):
for child in node.children:
if child.type in ('async', 'generator', 'static', 'abstract', 'override'):
modifiers.append(get_node_text(child))
elif child.type == 'accessibility_modifier':
modifiers.append(get_node_text(child))
elif lang == 'python':
for child in node.children:
if child.type == 'decorator':
dec_text = get_node_text(child)
if 'staticmethod' in dec_text:
modifiers.append('staticmethod')
elif 'classmethod' in dec_text:
modifiers.append('classmethod')
elif 'property' in dec_text:
modifiers.append('property')
else:
modifiers.append(dec_text)
elif lang == 'java':
for child in node.children:
if child.type in ('modifiers',):
for gc in child.children:
modifiers.append(get_node_text(gc))
elif lang == 'go':
if node.child_by_field_name('receiver'):
modifiers.append('method')
return modifiers
def calc_cyclomatic_complexity(node) -> int:
"""Estimate cyclomatic complexity from AST branching. (Feature 7)"""
complexity = 1 # Base
branch_nodes = ['if_statement', 'elif_clause', 'else_clause', 'for_statement',
'while_statement', 'try_statement', 'except_clause',
'if', 'elif', 'else', 'for', 'while', 'switch', 'case',
'conditional_expression', 'ternary_expression',
'catch_clause', 'match', 'when', 'guard']
logical_ops = ['and', 'or', '&&', '||']
def count_branches(n):
nonlocal complexity
if n.type in branch_nodes:
complexity += 1
if n.type == 'binary_expression':
for child in n.children:
if child.type == 'and' or child.type == 'or':
complexity += 1
for child in n.children:
count_branches(child)
count_branches(node)
return complexity
def calc_max_nesting(node, lang: str, depth: int = 0) -> int:
"""Calculate maximum nesting depth. (Feature 7)"""
nest_types = ['block', 'statement_block', 'if_statement', 'for_statement',
'while_statement', 'function_definition', 'function_declaration',
'class_definition', 'class_declaration', 'try_statement',
'switch_statement', 'match_statement']
max_depth = depth
for child in node.children:
if child.type in nest_types:
child_depth = calc_max_nesting(child, lang, depth + 1)
max_depth = max(max_depth, child_depth)
else:
child_depth = calc_max_nesting(child, lang, depth)
max_depth = max(max_depth, child_depth)
return max_depth
# Language-specific symbol extraction patterns
# Maps language to (function_node_types, class_node_types, identifier_node_types)
LANGUAGE_PATTERNS = {
'python': {
'functions': ['function_definition'],
'classes': ['class_definition'],
'name_nodes': ['identifier'],
'calls': ['call'],
},
'javascript': {
'functions': ['function_declaration', 'function', 'method_definition', 'arrow_function'],
'classes': ['class_declaration'],
'name_nodes': ['identifier', 'property_identifier'],
'calls': ['call_expression'],
},
'typescript': {
'functions': ['function_declaration', 'function', 'method_definition', 'arrow_function'],
'classes': ['class_declaration'],
'name_nodes': ['identifier', 'property_identifier', 'type_identifier'],
'calls': ['call_expression'],
},
'java': {
'functions': ['method_declaration', 'constructor_declaration'],
'classes': ['class_declaration', 'interface_declaration', 'enum_declaration'],
'name_nodes': ['identifier'],
'calls': ['method_invocation'],
},
'c': {
'functions': ['function_definition'],
'classes': ['struct_specifier', 'union_specifier'],
'name_nodes': ['identifier'],
'calls': ['call_expression'],
},
'cpp': {
'functions': ['function_definition', 'function_declarator'],
'classes': ['class_specifier', 'struct_specifier'],
'name_nodes': ['identifier', 'field_identifier', 'type_identifier'],
'calls': ['call_expression'],
},
'c_sharp': {
'functions': ['method_declaration', 'constructor_declaration'],
'classes': ['class_declaration', 'interface_declaration', 'struct_declaration'],
'name_nodes': ['identifier'],
'calls': ['invocation_expression'],
},
'go': {
'functions': ['function_declaration', 'method_declaration', 'func_literal'],
'classes': ['type_declaration', 'type_spec'],
'name_nodes': ['identifier', 'type_identifier', 'field_identifier'],
'calls': ['call_expression'],
},
'ruby': {
'functions': ['method', 'singleton_method'],
'classes': ['class', 'module'],
'name_nodes': ['identifier', 'constant'],
'calls': ['call'],
},
'php': {
'functions': ['function_definition', 'method_declaration'],
'classes': ['class_declaration', 'interface_declaration', 'trait_declaration'],
'name_nodes': ['name', 'variable_name'],
'calls': ['function_call_expression', 'scoped_call_expression', 'member_call_expression'],
},
'rust': {
'functions': ['function_item', 'function_signature_item'],
'classes': ['struct_item', 'enum_item', 'trait_item', 'impl_item'],
'name_nodes': ['identifier'],
'calls': ['call_expression'],
},
'swift': {
'functions': ['function_declaration'],
'classes': ['class_declaration', 'struct_declaration', 'enum_declaration', 'protocol_declaration'],
'name_nodes': ['simple_identifier'],
'calls': ['call_expression'],
},
'kotlin': {
'functions': ['function_declaration'],
'classes': ['class_declaration', 'object_declaration', 'interface_declaration'],
'name_nodes': ['simple_identifier'],
'calls': ['call_expression'],
},
'scala': {
'functions': ['function_definition'],
'classes': ['class_definition', 'object_definition', 'trait_definition'],
'name_nodes': ['identifier'],
'calls': ['call_expression'],
},
'java': {
'functions': ['method_declaration'],
'classes': ['class_declaration', 'interface_declaration', 'enum_declaration'],
'name_nodes': ['identifier'],
'calls': ['method_invocation'],
},
'lua': {
'functions': ['function_declaration', 'function_definition'],
'classes': ['table_constructor'],
'name_nodes': ['identifier'],
'calls': ['function_call'],
},
'dart': {
'functions': ['function_declaration', 'method_declaration'],
'classes': ['class_definition'],
'name_nodes': ['identifier'],
'calls': ['function_expression_invocation', 'selector_invocation'],
},
'elixir': {
'functions': ['call', 'do_block'],
'classes': ['alias'],
'name_nodes': ['identifier', 'alias'],
'calls': ['call'],
},
'haskell': {
'functions': ['function'],
'classes': ['data_type', 'class'],
'name_nodes': ['variable', 'constructor'],
'calls': ['term'],
},
'ocaml': {
'functions': ['value_definition'],
'classes': ['class_definition', 'class_type_definition'],
'name_nodes': ['value_name', 'type_constructor'],
'calls': ['infix_operator', 'prefix_operator'],
},
'julia': {
'functions': ['function_definition'],
'classes': ['struct_definition'],
'name_nodes': ['identifier'],
'calls': ['call_expression'],
},
'r': {
'functions': ['function_definition'],
'classes': [],
'name_nodes': ['identifier'],
'calls': ['call'],
},
'perl': {
'functions': ['function_definition', 'method_declaration'],
'classes': ['package_declaration'],
'name_nodes': ['identifier'],
'calls': ['function_call_expression'],
},
'bash': {
'functions': ['function_definition'],
'classes': [],
'name_nodes': ['variable_name'],
'calls': ['command'],
},
'sql': {
'functions': ['function_definition'],
'classes': ['create_table', 'create_view'],
'name_nodes': ['object_reference', 'identifier'],
'calls': [],
},
}
def get_language_patterns(lang):
"""Get AST patterns for a language."""
# Return language-specific patterns or generic fallback
return LANGUAGE_PATTERNS.get(lang, {
'functions': ['function_definition', 'function_declaration', 'function'],
'classes': ['class_definition', 'class_declaration', 'class', 'struct'],
'name_nodes': ['identifier', 'name'],
'calls': ['call', 'call_expression', 'invocation'],
})
def extract_symbols_from_node(node, lang, patterns, content: bytes) -> dict:
"""Extract comprehensive symbol info: name, calls, byte ranges, signature, params, docstring, metrics. (Features 3,4,5,7)"""
name_node = None
for child in node.children:
if child.type in patterns['name_nodes']:
name_node = child
break
if not name_node:
for child in find_nodes(node, patterns['name_nodes']):
name_node = child
break
if not name_node:
return None
name = get_node_text(name_node)
if not name or len(name) > 100:
return None
# Feature 3: Byte ranges
byte_range = extract_byte_range(node)
# Feature 4: Signature, parameters, return type, modifiers
signature = extract_signature(node, content)
parameters = extract_parameters(node, lang) if node.type in patterns.get('functions', []) else []
return_type = extract_return_type(node, lang) if node.type in patterns.get('functions', []) else None
modifiers = extract_modifiers(node, lang)
# Feature 5: Docstring and comments
docstring = extract_docstring(node, lang)
comments = extract_comments_in_body(node, lang, content)
# Calls
calls = []
call_nodes = find_nodes(node, patterns['calls'])
for call_node in call_nodes:
for child in call_node.children:
if child.type in patterns['name_nodes']:
call_name = get_node_text(child)
if call_name and len(call_name) < 100:
calls.append(call_name)
# Feature 7: Metrics
cyclomatic_complexity = calc_cyclomatic_complexity(node)
max_nesting = calc_max_nesting(node, lang)
return {
'name': name,
'byteRange': byte_range,
'signature': signature,
'parameters': parameters,
'returnType': return_type,
'modifiers': modifiers,
'docstring': docstring,
'comments': comments,
'calls': list(set(calls)),
'metrics': {
'cyclomaticComplexity': cyclomatic_complexity,
'maxNestingDepth': max_nesting,
}
}
# ============================================================
# Feature 8: Semantic relationship extraction
# ============================================================
def extract_semantic_relationships(node, lang, patterns, content: bytes) -> dict:
"""Extract inheritance, implementation, overrides. (Feature 8)"""
rels = {'extends': [], 'implements': [], 'overrides': []}
if lang in ('typescript', 'javascript'):
# class Foo extends Bar implements Baz
for child in node.children:
if child.type == 'class_heritage':
for hc in child.children:
if hc.type == 'extends_clause':
for gc in hc.children:
if gc.type in ('identifier', 'type_identifier'):
rels['extends'].append(get_node_text(gc))
elif hc.type == 'implements_clause':
for gc in hc.children:
if gc.type == 'type_identifier':
rels['implements'].append(get_node_text(gc))
elif lang == 'java':
for child in node.children:
if child.type == 'superclass':
for gc in child.children:
if gc.type == 'type_identifier':
rels['extends'].append(get_node_text(gc))
elif child.type == 'superinterfaces':
for gc in child.children:
if gc.type == 'type_identifier':
rels['implements'].append(get_node_text(gc))
elif lang == 'python':
# class Foo(Bar, Baz)
for child in node.children:
if child.type == 'argument_list':
for gc in child.children:
if gc.type == 'identifier':
rels['extends'].append(get_node_text(gc))
elif lang == 'go':
# Embedding (implicit inheritance)
for child in node.children:
if child.type == 'field_declaration_list':
for gc in child.children:
if gc.type == 'field_declaration' and gc.child_count > 0:
first = gc.child(0)
if first.type == 'type_identifier':
rels['extends'].append(get_node_text(first))
elif lang == 'rust':
# impl Trait for Type
if node.type == 'impl_item':
for child in node.children:
if child.type == 'type_identifier':
rels['implements'].append(get_node_text(child))
return rels
def extract_inheritance_info(data: dict):
"""Build inheritance graph from collected symbols. (Feature 8)"""
inheritance = []
for sym_id, sym in data['symbols'].items():
rels = sym.get('semanticRelations', {})
if rels.get('extends'):
for parent in rels['extends']:
# Try to resolve parent to actual symbol
parent_id = None
for sid, s in data['symbols'].items():
if s['name'] == parent and s['type'] == 'class':
parent_id = sid
break
inheritance.append({
'child': sym_id,
'parent': parent,
'parentResolved': parent_id
})
if rels.get('implements'):
for iface in rels['implements']:
iface_id = None
for sid, s in data['symbols'].items():
if s['name'] == iface and s['type'] == 'class':
iface_id = sid
break
inheritance.append({
'child': sym_id,
'parent': iface,
'parentResolved': iface_id,
'relation': 'implements'
})
return inheritance
def extract_imports(tree, lang):
"""Extract import/dependency statements from the AST."""
imports = []
import_node_types = [
'import_statement', 'import_from_statement', 'import_declaration',
'import_spec', 'namespace_import_declaration', 'named_imports',
'require_expression', 'include_statement',
'package_declaration', 'use_statement'
]
import_nodes = find_nodes(tree.root_node, import_node_types)
for node in import_nodes:
string_nodes = find_nodes(node, ['string', 'string_literal', 'raw_string_literal'])
for str_node in string_nodes:
imp = get_node_text(str_node).strip("'\"`@")
if imp and len(imp) < 200:
imports.append(imp)
if not string_nodes:
id_nodes = find_nodes(node, ['identifier', 'module', 'dotted_name', 'scoped_identifier'])
for id_node in id_nodes:
imp = get_node_text(id_node)
if imp and len(imp) < 200:
imports.append(imp)
return list(set(imports))
def calc_file_metrics(symbols: list, content: bytes) -> dict:
"""Calculate file-level quality metrics. (Feature 7)"""
total_complexity = sum(s.get('metrics', {}).get('cyclomaticComplexity', 0) for s in symbols)
total_funcs = len([s for s in symbols if s['type'] in ('function', 'method')])
total_classes = len([s for s in symbols if s['type'] == 'class'])
return {
'totalFunctions': total_funcs,
'totalClasses': total_classes,
'avgComplexity': round(total_complexity / total_funcs, 1) if total_funcs > 0 else 0,
'maxComplexity': max((s.get('metrics', {}).get('cyclomaticComplexity', 0) for s in symbols), default=0),
}
def sanitize_name(name: str) -> str:
return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower().strip('_')
def get_symbol_id(file_path: str, symbol_name: str) -> str:
return f"{sanitize_name(file_path)}_{sanitize_name(symbol_name)}"
def parse_file(file_path: Path, project_root: Path, data: dict):
"""Parse a single file and extract symbols, imports, relationships. (Features 3,4,5,7,8)"""
parser, lang, language = get_parser_for_file(file_path)
if not parser:
return
rel_path = str(file_path.relative_to(project_root))
try:
content = file_path.read_bytes()
except Exception as e:
print(f" Warning: Could not read {rel_path}: {e}")
return
try:
tree = parser.parse(content)
except Exception as e:
print(f" Warning: Could not parse {rel_path}: {e}")
return
if not tree or not tree.root_node:
return
data['files'][rel_path] = {
'path': rel_path,
'language': lang,
'symbols': [],
'imports': [],
'used_by': [],
'metrics': {}
}
patterns = get_language_patterns(lang)
# Extract functions/methods
func_nodes = find_nodes(tree.root_node, patterns['functions'])
for func_node in func_nodes:
info = extract_symbols_from_node(func_node, lang, patterns, content)
if info:
sym_type = 'function'
class_node_types = patterns.get('classes', [])
parent = func_node.parent
while parent:
if parent.type in class_node_types:
sym_type = 'method'
break
parent = parent.parent
# Feature 8: Semantic relationships
semantic = extract_semantic_relationships(func_node, lang, patterns, content) if sym_type == 'class' else {}
sym_id = get_symbol_id(rel_path, info['name'])
if sym_id not in data['symbols']:
data['symbols'][sym_id] = {
'name': info['name'],
'type': sym_type,
'file': rel_path,
'language': lang,
'byteRange': info['byteRange'], # Feature 3
'signature': info['signature'], # Feature 4
'parameters': info['parameters'], # Feature 4
'returnType': info['returnType'], # Feature 4
'modifiers': info['modifiers'], # Feature 4
'docstring': info['docstring'], # Feature 5
'comments': info['comments'], # Feature 5
'calls': info['calls'],
'called_by': [],
'metrics': info['metrics'], # Feature 7
'semanticRelations': semantic, # Feature 8
}
data['files'][rel_path]['symbols'].append(sym_id)
# Extract classes/structs/interfaces
class_nodes = find_nodes(tree.root_node, patterns['classes'])
for class_node in class_nodes:
info = extract_symbols_from_node(class_node, lang, patterns, content)
if info:
# Feature 8: Semantic relationships for classes
semantic = extract_semantic_relationships(class_node, lang, patterns, content)
sym_id = get_symbol_id(rel_path, info['name'])
if sym_id not in data['symbols']:
data['symbols'][sym_id] = {
'name': info['name'],
'type': 'class',
'file': rel_path,
'language': lang,
'byteRange': info['byteRange'],
'signature': info['signature'],
'docstring': info['docstring'],
'comments': info['comments'],
'calls': [],
'called_by': [],
'metrics': info['metrics'],
'semanticRelations': semantic,
}
data['files'][rel_path]['symbols'].append(sym_id)
# Extract imports
data['files'][rel_path]['imports'] = extract_imports(tree, lang)
# Feature 7: File-level metrics
file_symbols = [data['symbols'][sid] for sid in data['files'][rel_path]['symbols'] if sid in data['symbols']]
data['files'][rel_path]['metrics'] = calc_file_metrics(file_symbols, content)
def extract_relations(data: dict):
"""Resolve symbol calls to actual symbol IDs."""
# Build a name-to-symbol-id index
name_to_sym_id = {}
for sym_id, sym in data['symbols'].items():
if sym['name'] not in name_to_sym_id:
name_to_sym_id[sym['name']] = []
name_to_sym_id[sym['name']].append(sym_id)
# Resolve calls - first collect all call resolutions
for sym_id, sym in list(data['symbols'].items()):
call_names = sym.get('calls', []) # Get call names
sym['calls'] = [] # Reset to store resolved symbol IDs
for call_name in call_names:
if call_name in name_to_sym_id:
for target_id in name_to_sym_id[call_name]:
if target_id != sym_id: # Don't add self-references
if target_id not in sym['calls']:
sym['calls'].append(target_id)
if sym_id not in data['symbols'][target_id]['called_by']:
data['symbols'][target_id]['called_by'].append(sym_id)
# Build file-level dependencies from imports
for path, info in data['files'].items():
for imp in info['imports']:
for target_path in data['files']:
if path != target_path: # Don't add self-references
# Match if import path is in target path or vice versa
imp_base = imp.split('.')[-1] if '.' in imp else imp
target_base = Path(target_path).stem
if imp_base == target_base or imp in target_path or target_path in imp:
if path not in data['files'][target_path]['used_by']:
data['files'][target_path]['used_by'].append(path)
def generate_markdown(out: Path, data: dict):
"""Generate markdown files with enhanced symbol info. (Features 3,4,5,7,8,14)"""
if not data['files']:
print("Warning: No files found to generate markdown.")
return
print(f"\nGenerating markdown files...")
# Feature 14: Build domain groups
domain_groups = build_domain_groups(data)
# Generate meta overview
from datetime import datetime
(out / "00_meta").mkdir(parents=True, exist_ok=True)
lang_dist = {}
for path, info in data['files'].items():
lang = info.get('language', 'unknown')
lang_dist[lang] = lang_dist.get(lang, 0) + 1
meta_content = f"""# Project Meta
**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
## Overview
- **Total Files:** {len(data['files'])}
- **Total Symbols:** {len(data['symbols'])}
- **Languages:** {', '.join(sorted(lang_dist.keys()))}
## Language Distribution
{chr(10).join(f'- **{lang}:** {count} files' for lang, count in sorted(lang_dist.items(), key=lambda x: -x[1]))}
## Symbol Breakdown
- **Functions/Methods:** {sum(1 for s in data['symbols'].values() if s['type'] in ('function', 'method'))}
- **Classes:** {sum(1 for s in data['symbols'].values() if s['type'] == 'class')}