-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcw.py
More file actions
2759 lines (2441 loc) · 119 KB
/
Copy pathcw.py
File metadata and controls
2759 lines (2441 loc) · 119 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
# -*- coding: utf-8 -*-
"""
codewiki (cw.py) — 코드 프로젝트용 AI Wiki 툴킷의 결정론적 부분.
의존성: Python 3.8+ 표준 라이브러리만 사용. (universal-ctags가 있으면 C/C++ 정밀도 향상)
명령:
cw.py init <프로젝트경로> 위키 골격(wiki/)과 설정(.codewiki/) 설치
cw.py index [경로] 소스에서 사실(facts) 추출 → .codewiki/facts.db
cw.py stubs [경로] wiki/files/ 아래 파일 stub 자동 생성 (편집 금지 영역)
cw.py map [경로] 모듈 후보/중요 파일 요약 출력 (AI에게 줄 지도)
cw.py lint [경로] 위키 문서의 anchor·라벨·최신성 검사
cw.py update [경로] git diff 기반으로 낡은(stale) 문서 찾기 + 재색인
cw.py update --mark-done AI 갱신 완료 후 현재 커밋을 기준점으로 기록
cw.py status [경로] 색인 상태 요약
cw.py parse-report [경로] 파서가 코드를 얼마나 읽어냈는지 진단 + 권고
cw.py try-macros [경로] 범인 매크로를 하나씩 지워보고 안전한 것만 고름
cw.py install-skills [경로] Claude Code 스킬 설치 (setup 이 자동으로 해줌)
cw.py log [경로] [--gaps] 기록장 — 위키에 없어서 코드를 열어본 질문
설계 원칙:
- 코드는 절대 위키로 복사하지 않는다. anchor(경로:라인, sym:경로#이름)로 참조만 한다.
- 기계가 뽑은 사실(facts.db)은 갱신하지 않고 매번 재생성한다.
- DB에 없다는 것은 "존재하지 않음"이 아니라 "확인 못 함"이다. (비대칭 규칙)
"""
import argparse
import ast
from collections import namedtuple
import bisect
import fnmatch
import hashlib
import json
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import warnings
from pathlib import Path
TOOLKIT_DIR = Path(__file__).resolve().parent
LANG_BY_EXT = {
".py": "python",
".c": "c", ".h": "c",
".cpp": "cpp", ".cc": "cpp", ".cxx": "cpp",
".hpp": "cpp", ".hh": "cpp", ".hxx": "cpp", ".inl": "cpp",
".idl": "idl",
".fidl": "idl", # Franca IDL(SOME/IP 계열) — interface 이름 추출 목적
}
DEFAULT_EXCLUDES = [
".git", ".codewiki", "wiki", "build", "cmake-build-*", "out", "dist",
"__pycache__", ".venv", "venv", "node_modules", "third_party", "external",
".idea", ".vscode",
]
# 파일 이름 기준 제외 — 생성 코드와 코드 생성용 템플릿.
# 사람이 문서화할 대상이 아니고, 파싱해봐야 오류만 쌓이며,
# 파일 수를 부풀려 커버리지 비율까지 왜곡한다.
# (.codewiki/config.json 의 "exclude_files" 로 덮어쓸 수 있다)
DEFAULT_EXCLUDE_FILES = [
"*.pb.h", "*.pb.cc", "*.pb.c", # protobuf 생성 코드
"*.pb-c.h", "*.pb-c.c", # protobuf-c
"*.in.c", "*.in.h", "*.in.cpp", "*.in.hpp", # 코드 생성 템플릿 (C 문법 아님)
"*_generated.h", "*_generated.cc", # flatbuffers 등
"moc_*.cpp", "ui_*.h", "qrc_*.cpp", # Qt 생성 코드
"*.pyc",
]
# ---------------------------------------------------------------- 공통 유틸
def die(msg):
print("오류: " + msg, file=sys.stderr)
sys.exit(1)
def sha_of(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()[:12]
def read_source(p: Path):
"""소스 파일 읽기. UTF-8 → CP949(한국어 레거시) → latin-1 순서로 시도.
반환: (raw bytes, 디코딩된 text, 사용된 인코딩)"""
raw = p.read_bytes()
for enc in ("utf-8", "cp949", "latin-1"):
try:
return raw, raw.decode(enc), enc
except UnicodeDecodeError:
continue
return raw, raw.decode("utf-8", errors="replace"), "utf-8(replace)"
def run_git(root: Path, *args):
"""git 명령 실행. git 저장소가 아니거나 실패하면 None."""
try:
r = subprocess.run(["git", "-C", str(root)] + list(args),
capture_output=True, text=True, timeout=30)
if r.returncode != 0:
return None
return r.stdout.strip()
except Exception:
return None
def load_config(root: Path) -> dict:
cfg_path = root / ".codewiki" / "config.json"
cfg = {"exclude_dirs": DEFAULT_EXCLUDES, "extra_source_dirs": [],
"ignore_macros": []}
if cfg_path.exists():
try:
cfg.update(json.loads(cfg_path.read_text(encoding="utf-8")))
except Exception as e:
die(f"config.json 파싱 실패: {e}")
return cfg
def is_excluded(rel_parts, patterns):
for part in rel_parts:
for pat in patterns:
if fnmatch.fnmatch(part, pat):
return True
return False
_LAST_SKIPPED_GENERATED = 0 # 직전 iter_source_files 가 건너뛴 생성 코드 수
def iter_source_files(root: Path, cfg: dict):
global _LAST_SKIPPED_GENERATED
_LAST_SKIPPED_GENERATED = 0
excludes = cfg.get("exclude_dirs", DEFAULT_EXCLUDES)
file_excludes = cfg.get("exclude_files", DEFAULT_EXCLUDE_FILES)
for dirpath, dirnames, filenames in os.walk(root):
rel = Path(dirpath).relative_to(root)
dirnames[:] = [d for d in dirnames
if not is_excluded([d], excludes)]
if rel.parts and is_excluded(rel.parts, excludes):
dirnames[:] = []
continue
for fn in sorted(filenames):
ext = Path(fn).suffix.lower()
if ext not in LANG_BY_EXT:
continue
if any(fnmatch.fnmatch(fn, pat) for pat in file_excludes):
_LAST_SKIPPED_GENERATED += 1
continue
yield Path(dirpath) / fn
def db_path(root: Path) -> Path:
return root / ".codewiki" / "facts.db"
def open_db(root: Path, create=False) -> sqlite3.Connection:
p = db_path(root)
if not p.exists() and not create:
die("facts.db가 없습니다. 먼저 `cw.py index`를 실행하세요.")
p.parent.mkdir(parents=True, exist_ok=True)
con = sqlite3.connect(str(p))
con.execute("PRAGMA journal_mode=WAL")
return con
SCHEMA = """
CREATE TABLE IF NOT EXISTS files(
id INTEGER PRIMARY KEY, path TEXT UNIQUE, sha TEXT, lang TEXT, loc INTEGER);
CREATE TABLE IF NOT EXISTS symbols(
id INTEGER PRIMARY KEY, file_id INTEGER, name TEXT, kind TEXT,
signature TEXT, line_start INTEGER, line_end INTEGER, provenance TEXT);
CREATE TABLE IF NOT EXISTS edges(
id INTEGER PRIMARY KEY, src_file TEXT, src_symbol TEXT,
dst_name TEXT, dst_file TEXT, kind TEXT, provenance TEXT, confidence TEXT);
CREATE TABLE IF NOT EXISTS gaps(
id INTEGER PRIMARY KEY, file TEXT, line INTEGER, kind TEXT,
detail TEXT, affects_symbol TEXT,
status TEXT NOT NULL DEFAULT 'open', resolution TEXT, evidence TEXT);
CREATE INDEX IF NOT EXISTS idx_gap_file ON gaps(file);
CREATE INDEX IF NOT EXISTS idx_gap_sym ON gaps(affects_symbol);
CREATE INDEX IF NOT EXISTS idx_gap_kind ON gaps(kind);
CREATE INDEX IF NOT EXISTS idx_sym_file ON symbols(file_id);
CREATE INDEX IF NOT EXISTS idx_edge_src ON edges(src_file);
CREATE INDEX IF NOT EXISTS idx_edge_dst ON edges(dst_file);
CREATE INDEX IF NOT EXISTS idx_edge_dstname ON edges(dst_name);
CREATE INDEX IF NOT EXISTS idx_sym_name ON symbols(name);
"""
# ---------------------------------------------------------------- 파서들
# 원칙: 여기서 뽑은 것은 "찾은 사실"이다. 못 찾은 것은 없다는 뜻이 아니다.
def parse_python(path: Path, text: str):
"""stdlib ast 사용 — python 심볼/임포트는 신뢰도 높음(confirmed)."""
symbols, edges = [], []
try:
# 색인 대상 파일의 문법 경고(invalid escape sequence 등)는
# 그 프로젝트의 문제이지 색인 오류가 아니므로 출력하지 않는다.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
tree = ast.parse(text)
except SyntaxError:
return symbols, edges
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
args = ", ".join(a.arg for a in node.args.args)
symbols.append((node.name, "function", f"def {node.name}({args})",
node.lineno, getattr(node, "end_lineno", node.lineno),
"python-ast"))
for sub in ast.walk(node):
if isinstance(sub, ast.Call):
fn = sub.func
callee = None
if isinstance(fn, ast.Name):
callee = fn.id
elif isinstance(fn, ast.Attribute):
callee = fn.attr
if callee:
# 이름 기반 호출: 어느 심볼로 가는지는 미해석 → inferred
edges.append((node.name, callee, None, "calls",
"python-ast", "inferred"))
elif isinstance(node, ast.ClassDef):
bases = ", ".join(getattr(b, "id", getattr(b, "attr", "?"))
for b in node.bases)
symbols.append((node.name, "class", f"class {node.name}({bases})",
node.lineno, getattr(node, "end_lineno", node.lineno),
"python-ast"))
elif isinstance(node, ast.Import):
for alias in node.names:
edges.append((None, alias.name, None, "imports",
"python-ast", "confirmed"))
elif isinstance(node, ast.ImportFrom):
mod = node.module or ""
edges.append((None, mod, None, "imports", "python-ast", "confirmed"))
return symbols, edges
RE_INCLUDE = re.compile(r'^\s*#\s*include\s*[<"]([^">]+)[">]', re.M)
RE_CLASS = re.compile(r'^\s*(?:template\s*<[^>]*>\s*)?(class|struct)\s+(\w+)'
r'(?![^{;\n]*;)', re.M)
# ---- C/C++ 스캐너 (정규식 휴리스틱 대체) ----------------------------------
# 방식: 주석·문자열·전처리 줄을 공백으로 지운 뒤(줄 번호 보존),
# 모든 '{'에 대해 바로 앞이 "이름(인자들)" 형태인지 뒤로 검사한다.
# 정규식 대비 개선: 여러 줄 시그니처, 생성자 초기화 리스트, 함수 끝 라인,
# 주석/문자열 속 가짜 코드 오탐 제거. 여전히 못 하는 것: 매크로 전개,
# 템플릿 인스턴스 해석, operator 오버로드 일부.
C_STRIP_RE = re.compile(
r'R"([^(\n]{0,16})\([\s\S]*?\)\1"' # C++11 raw string
r'|//[^\n]*' # 줄 주석
r'|/\*[\s\S]*?\*/' # 블록 주석
r'|"(?:\\.|[^"\\\n])*"' # 문자열
r"|'(?:\\.|[^'\\\n])*'" # 문자
r'|^[ \t]*#[^\n]*(?:\\\n[^\n]*)*', # 전처리 지시문(#define의 { 방지)
re.M)
CTRL_KEYWORDS = {"if", "for", "while", "switch", "return", "else", "do",
"case", "catch", "sizeof", "new", "delete", "defined",
"assert", "constexpr", "requires", "alignas", "decltype",
"alignof", "static_assert", "typeid"}
TRAILER_WORDS = {"const", "noexcept", "override", "final", "mutable",
"volatile", "throw", "try"}
def _blank_keep_newlines(m):
return "".join(c if c == "\n" else " " for c in m.group(0))
def blank_macros(text, names):
"""장식 매크로 이름을 같은 길이의 공백으로 지운다.
`MEDIA_PUBLIC void start_camera(int)` 처럼 타입 자리 앞에 붙는 매크로는
파서를 깨뜨려 선언 전체를 놓치게 만든다. 무엇으로 전개되는지는 알 필요가
없다 — 지우기만 하면 나머지가 그대로 읽힌다. (사내 실측: MEDIA_PUBLIC
1,002곳, ADSTDTFSIMD_FORCE_INLINE 254곳)
같은 길이의 공백으로 바꾸는 이유: 줄·열 번호가 원본과 어긋나면 구멍의
위치와 심볼의 줄 번호가 전부 틀어진다.
전처리기 지시문 줄(`#define`/`#ifdef`/`#undef`)은 건드리지 않는다.
정의 자체에서 이름을 지우면 그 줄이 새 오류가 된다.
"""
if not names:
return text
names = [n for n in names if n]
if not names:
return text
# 긴 이름부터 — C_VEC_MEM 이 C_VEC_MEM_EXT 의 앞부분을 먼저 먹으면 안 된다
rx = re.compile(r"\b(?:%s)\b" % "|".join(
re.escape(n) for n in sorted(set(names), key=len, reverse=True)))
out = []
for line in text.split("\n"):
if line.lstrip().startswith("#"):
out.append(line)
else:
out.append(rx.sub(lambda m: " " * len(m.group(0)), line))
return "\n".join(out)
def _match_back(s, i, close_ch, open_ch, limit_chars=6000):
"""s[i]==close_ch에서 짝이 되는 open_ch 인덱스. 실패/한도 초과 시 -1."""
depth = 0
limit = max(0, i - limit_chars)
while i >= limit:
c = s[i]
if c == close_ch:
depth += 1
elif c == open_ch:
depth -= 1
if depth == 0:
return i
i -= 1
return -1
def _ident_back(s, i):
"""s[i]에서 뒤로 (한정 가능한) 식별자 읽기 → (name, name_start_index)."""
j = i
while j >= 0:
c = s[j]
if c.isalnum() or c in "_~":
j -= 1
elif c == ":" and j >= 1 and s[j - 1] == ":":
j -= 2
else:
break
return s[j + 1:i + 1], j + 1
def _is_access_colon(s, k):
"""s[k]==':' 가 public:/private:/protected: 의 콜론인지."""
if k < 1:
return False
word, _ = _ident_back(s, k - 1)
return word in ("public", "private", "protected")
def _sig_before_brace(s, brace_pos):
"""'{' 직전이 함수 시그니처면 (name, name_pos, sig) 반환, 아니면 None."""
i = brace_pos - 1
for _ in range(40): # 초기화 리스트 멤버 수 상한
while i >= 0 and s[i].isspace():
i -= 1
if i < 0:
return None
c = s[i]
if c == ")":
op = _match_back(s, i, ")", "(")
if op < 0:
return None
j = op - 1
while j >= 0 and s[j].isspace():
j -= 1
if j < 0:
return None
name, ns = _ident_back(s, j)
if not name:
return None # 람다 `](){...}`, 캐스팅 등
base = name.split("::")[-1].lstrip("~")
if base in TRAILER_WORDS: # noexcept(...) 같은 꼬리 그룹
i = ns - 1
continue
if base in CTRL_KEYWORDS:
return None
# 생성자 초기화 리스트 항목( `: a_(1), b_(2)` )이면 더 뒤로.
# 단 `public:` 등 접근 지정자의 콜론은 초기화 리스트가 아니다.
k = ns - 1
while k >= 0 and s[k].isspace():
k -= 1
if k >= 0 and (s[k] == "," or
(s[k] == ":" and (k == 0 or s[k - 1] != ":")
and not _is_access_colon(s, k))):
i = k - 1
continue
sig = re.sub(r"\s+", " ", s[ns:i + 1]).strip()
return name, ns, sig[:120]
if c == "}": # 초기화 리스트의 brace-init `count_{0}` 건너뛰기
op = _match_back(s, i, "}", "{")
if op < 0:
return None
i = op - 1
continue
if c.isalnum() or c == "_":
name, ns = _ident_back(s, i)
if name in TRAILER_WORDS:
i = ns - 1
continue
if name.split("::")[-1] in CTRL_KEYWORDS:
return None # `return {};` 등
arrow = s.rfind("->", max(0, ns - 200), ns)
if arrow >= 0: # 후행 반환 타입 `-> std::vector<int>`
i = arrow - 1
continue
# 초기화 리스트의 brace-init 멤버 이름( `count_{0}` 의 count_ )
k = ns - 1
while k >= 0 and s[k].isspace():
k -= 1
if k >= 0 and (s[k] == "," or
(s[k] == ":" and (k == 0 or s[k - 1] != ":"))):
i = k - 1
continue
return None
if c in ">&*:":
arrow = s.rfind("->", max(0, i - 200), i)
if arrow >= 0:
i = arrow - 1
continue
return None
return None
return None
CALL_RE = re.compile(r"\b([A-Za-z_]\w{1,63})\s*\(")
CALL_NOISE = CTRL_KEYWORDS | TRAILER_WORDS | {
"int", "char", "float", "double", "void", "bool", "long", "short",
"unsigned", "signed", "auto", "size_t", "template", "operator",
"static_cast", "dynamic_cast", "reinterpret_cast", "const_cast"}
MAX_CALLS_PER_FUNC = 32
def _find_functions(stripped):
nl = [m.start() for m in re.finditer("\n", stripped)]
def line_of(pos):
return bisect.bisect_left(nl, pos) + 1
stack, pairs = [], {}
for m in re.finditer(r"[{}]", stripped):
if m.group() == "{":
stack.append(m.start())
elif stack:
pairs[stack.pop()] = m.start()
out, calls, seen = [], [], set()
for p in sorted(pairs):
hit = _sig_before_brace(stripped, p)
if hit:
name, ns, sig = hit
if ns in seen: # 초기화 리스트의 brace-init 등 내부 '{' 중복 방지
continue
seen.add(ns)
out.append((name, "function", sig,
line_of(ns), line_of(pairs[p]), "scanner"))
# 본문 속 호출 후보: `이름(` 패턴 — 어느 심볼로 가는지는 미해석
body = stripped[p:pairs[p]]
base = name.split("::")[-1]
found = set()
for cm in CALL_RE.finditer(body):
callee = cm.group(1)
if callee in CALL_NOISE or callee == base:
continue
found.add(callee)
if len(found) >= MAX_CALLS_PER_FUNC:
break
for callee in sorted(found):
calls.append((name, callee, None, "calls",
"scanner", "inferred"))
return out, calls
def parse_c_cpp(path: Path, text: str):
"""스캐너 휴리스틱 — 컴파일하지 않으므로 매크로 전개·템플릿 해석은 못 하고,
그 사실을 provenance='scanner'로 기록한다. universal-ctags가 있으면 대체됨."""
symbols, edges = [], []
for m in RE_INCLUDE.finditer(text): # 전처리 줄은 원본에서 추출
edges.append((None, m.group(1), None, "includes", "regex", "confirmed"))
stripped = C_STRIP_RE.sub(_blank_keep_newlines, text)
for m in RE_CLASS.finditer(stripped):
line = stripped.count("\n", 0, m.start()) + 1
symbols.append((m.group(2), m.group(1), m.group(0).strip()[:120],
line, line, "scanner"))
funcs, calls = _find_functions(stripped)
symbols += funcs
edges += calls
return symbols, edges
def parse_c_cpp_ctags(path: Path, text: str):
"""universal-ctags(JSON 출력 지원)가 있으면 사용 — regex보다 정확."""
try:
r = subprocess.run(
["ctags", "--output-format=json", "--fields=+neS",
"--languages=C,C++", "-f", "-", str(path)],
capture_output=True, text=True, timeout=30)
if r.returncode != 0:
return None
except Exception:
return None
symbols = []
kind_map = {"function": "function", "class": "class", "struct": "struct",
"member": "method", "prototype": "prototype",
"enum": "enum", "typedef": "typedef"}
for line in r.stdout.splitlines():
try:
t = json.loads(line)
except Exception:
continue
kind = kind_map.get(t.get("kind"))
if not kind:
continue
ln = t.get("line", 0)
symbols.append((t.get("name", "?"), kind,
(t.get("signature") or t.get("pattern") or "")[:120],
ln, t.get("end", ln), "ctags"))
edges = [(None, m.group(1), None, "includes", "regex", "confirmed")
for m in RE_INCLUDE.finditer(text)]
return symbols, edges
RE_IDL_MODULE = re.compile(r'^\s*module\s+(\w+)', re.M)
RE_IDL_IFACE = re.compile(r'^\s*(?:abstract\s+|local\s+)?interface\s+(\w+)', re.M)
RE_IDL_STRUCT = re.compile(r'^\s*struct\s+(\w+)', re.M)
RE_IDL_ENUM = re.compile(r'^\s*enum\s+(\w+)', re.M)
RE_IDL_TYPEDEF = re.compile(r'^\s*typedef\s+[\w:<>,\s]+?(\w+)\s*(?:\[[^\]]*\])?\s*;', re.M)
RE_IDL_METHOD = re.compile(
r'^\s*(?:oneway\s+)?(?:void|[\w:]+(?:\s*<[^>]*>)?)\s+(\w+)\s*\(', re.M)
IDL_METHOD_BLACKLIST = {"module", "interface", "struct", "enum", "typedef",
"exception", "union", "switch", "case", "if"}
def parse_idl(path: Path, text: str):
"""CORBA/DDS IDL — 문법이 단순해 정규식으로도 신뢰도가 상당히 높음."""
symbols, edges = [], []
for m in RE_INCLUDE.finditer(text):
edges.append((None, m.group(1), None, "includes", "regex", "confirmed"))
for rx, kind in [(RE_IDL_MODULE, "idl_module"), (RE_IDL_IFACE, "idl_interface"),
(RE_IDL_STRUCT, "idl_struct"), (RE_IDL_ENUM, "idl_enum"),
(RE_IDL_TYPEDEF, "idl_typedef")]:
for m in rx.finditer(text):
line = text.count("\n", 0, m.start()) + 1
symbols.append((m.group(1), kind, m.group(0).strip()[:120],
line, line, "regex"))
declared = {s[0] for s in symbols}
for m in RE_IDL_METHOD.finditer(text):
name = m.group(1)
if name in IDL_METHOD_BLACKLIST or name in declared:
continue
line = text.count("\n", 0, m.start()) + 1
symbols.append((name, "idl_method", m.group(0).strip()[:120],
line, line, "regex"))
return symbols, edges
_HAS_UCTAGS = None
def has_universal_ctags():
global _HAS_UCTAGS
if _HAS_UCTAGS is None:
try:
r = subprocess.run(["ctags", "--version"], capture_output=True,
text=True, timeout=10)
_HAS_UCTAGS = "Universal Ctags" in (r.stdout or "")
except Exception:
_HAS_UCTAGS = False
return _HAS_UCTAGS
# ---------------------------------------------------------------- tree-sitter
# 교체 이유는 정확도가 아니라 "못 읽은 것을 말해주는 능력"이다.
# 정규식 스캐너는 못 읽으면 조용히 넘어가므로, 자기가 뭘 놓쳤는지 모른다.
# tree-sitter는 해석 실패를 ERROR/MISSING 노드로 알려주고, 그것이
# 미해석 대장(gaps)의 재료가 된다.
_TS_CACHE = None # (languages_or_None, reason)
def _ts_load():
"""tree-sitter 로드 시도. 실패해도 예외를 밖으로 내보내지 않는다."""
try:
from tree_sitter import Language, Parser # noqa: F401
except ImportError:
return None, ("tree-sitter 미설치 → 내장 정규식 파서 사용. "
"정밀 모드를 쓰려면: pip install -r requirements-parser.txt")
try:
import tree_sitter_c
import tree_sitter_cpp
except ImportError:
return None, ("tree-sitter 문법 패키지 미설치 → 내장 정규식 파서 사용. "
"pip install -r requirements-parser.txt")
try:
from tree_sitter import Language, Parser
langs = {"c": Language(tree_sitter_c.language()),
"cpp": Language(tree_sitter_cpp.language())}
Parser(langs["c"]) # ABI 호환성은 여기서 터진다
return langs, "tree-sitter 사용 가능 (정밀 모드)"
except Exception as e:
return None, (f"tree-sitter 버전 충돌 → 내장 정규식 파서 사용 ({e}). "
"requirements-parser.txt 의 핀 버전으로 맞추세요: "
"pip install -r requirements-parser.txt")
def _ts_get():
global _TS_CACHE
if _TS_CACHE is None:
_TS_CACHE = _ts_load()
return _TS_CACHE
def ts_languages():
"""{'c': Language, 'cpp': Language} 또는 None."""
return _ts_get()[0]
def ts_status():
"""(사용가능여부, 사람이 읽는 사유)."""
langs, reason = _ts_get()
return (langs is not None), reason
_TS_NAME_NODES = ("identifier", "field_identifier", "qualified_identifier",
"operator_name", "destructor_name", "type_identifier")
# C 관례상 매크로는 대문자다. 파싱 오류가 난 줄의 대문자 식별자를 모으면
# "무엇 때문에 못 읽었나"의 후보가 나온다. 완벽한 판별은 아니지만
# "다음에 뭘 처리할지"를 정하는 데는 충분하다.
_MACROISH_RE = re.compile(r"\b([A-Z][A-Z0-9_]{2,})\b")
# 매크로 모양이지만 범인일 리 없는 흔한 상수·타입 — 빼지 않으면 목록이 이걸로 덮인다
_MACROISH_IGNORE = {
"NULL", "TRUE", "FALSE", "EOF", "SEEK_SET", "SEEK_CUR", "SEEK_END",
"INT_MAX", "INT_MIN", "UINT_MAX", "LONG_MAX", "SIZE_MAX", "CHAR_BIT",
"UINT8_MAX", "UINT16_MAX", "UINT32_MAX", "UINT64_MAX",
"INT8_MAX", "INT16_MAX", "INT32_MAX", "INT64_MAX",
"M_PI", "RAND_MAX", "BUFSIZ", "STDIN_FILENO", "STDOUT_FILENO",
"STDERR_FILENO", "EXIT_SUCCESS", "EXIT_FAILURE",
}
def _culprit_macros(lines, line_idx):
"""오류가 난 줄(과 바로 앞줄)에서 매크로 후보를 뽑는다.
선언이 여러 줄에 걸칠 수 있어 앞줄까지 본다.
"""
lo = max(0, line_idx - 1)
ctx = "\n".join(lines[lo:line_idx + 1])
out = []
for m in _MACROISH_RE.findall(ctx):
if m not in _MACROISH_IGNORE and m not in out:
out.append(m)
return out[:4] # 한 오류당 최대 4개까지만
def _ts_is_include_guard(node, src):
"""인클루드 가드(#ifndef FOO_H / #define FOO_H)인가?
가드는 거의 모든 헤더에 있으므로 이걸 조건부 컴파일 구멍으로 세면
판정이 항상 '나쁨'이 되고 커버리지 경고가 노이즈가 되어 무시당한다.
가드는 빌드 변형이 아니라 관용구이므로 제외한다.
판별: 최상위 preproc_ifdef 이면서 #else 가 없고,
안쪽 첫 지시문이 같은 이름의 #define 인 것.
"""
if node.type != "preproc_ifdef":
return False
if node.parent is None or node.parent.type != "translation_unit":
return False
if node.child_by_field_name("alternative") is not None:
return False
nm = node.child_by_field_name("name")
if nm is None:
return False
guard = src[nm.start_byte:nm.end_byte].decode("utf-8", "replace")
for ch in node.children:
if ch.type in ("preproc_def", "preproc_function_def"):
d = ch.child_by_field_name("name")
return (d is not None and
src[d.start_byte:d.end_byte].decode(
"utf-8", "replace") == guard)
if ch.type not in ("#ifndef", "#ifdef", "identifier", "comment"):
return False
return False
def _ts_decl_name(node, src):
"""function_definition 에서 (이름, 매크로로_뭉개짐) 추출.
매크로가 시그니처에 끼면 tree-sitter 는 declarator 를
parenthesized_declarator 로 파싱한다. 이때 진짜 이름은 그 앞의
type_identifier 에 들어간다. 예:
FUNC(void, RTE_CODE) Rte_Write_Sig(VAR(uint8, AUTOMATIC) v)
→ type_identifier[Rte_Write_Sig] + parenthesized_declarator[(...)]
이 모양은 ERROR 노드 없이도 나타나므로 has_error 만으로는 못 잡는다.
"""
d = node.child_by_field_name("declarator")
while d is not None:
if d.type == "parenthesized_declarator":
for ch in node.children:
if ch is d:
break
if ch.type == "type_identifier":
return src[ch.start_byte:ch.end_byte].decode(
"utf-8", "replace"), True
return None, True
if d.type in _TS_NAME_NODES:
return src[d.start_byte:d.end_byte].decode("utf-8", "replace"), False
nxt = d.child_by_field_name("declarator")
if nxt is None:
for ch in d.children:
if ch.type in _TS_NAME_NODES:
return src[ch.start_byte:ch.end_byte].decode(
"utf-8", "replace"), False
return None, True
d = nxt
return None, True
def parse_c_cpp_ts(path: Path, text: str, lang: str):
"""tree-sitter 파서. (symbols, edges, gaps) 반환. 불가 시 None.
gaps 항목은 (kind, line, detail, affects_symbol) 4-튜플.
"""
langs = ts_languages()
if langs is None:
return None
from tree_sitter import Parser
src = text.encode("utf-8", "replace")
try:
tree = Parser(langs["cpp" if lang == "cpp" else "c"]).parse(src)
except Exception:
return None
symbols, edges, gaps = [], [], []
guard_names = set() # 인클루드 가드의 #define 은 심볼이 아니다
text_lines = text.split("\n")
def txt(n):
return src[n.start_byte:n.end_byte].decode("utf-8", "replace")
def _decl_ident(node):
"""declaration/declarator 사슬을 타고 내려가 이름 노드를 찾는다."""
d = node
seen = 0
while d is not None and seen < 12:
seen += 1
if d.type in _TS_NAME_NODES:
return d
nxt = d.child_by_field_name("declarator")
if nxt is None:
for ch in d.children:
if ch.type in _TS_NAME_NODES:
return ch
return None
d = nxt
return None
def walk(n, enclosing, in_func=False):
line = n.start_point[0] + 1
cur = enclosing
# ERROR/MISSING 은 별도 if 로 둔다. elif 로 묶으면 ERROR 노드 안의
# 함수 정의를 놓친다.
if n.is_missing:
gaps.append(("parse_missing", line,
"문법상 빠진 토큰 '%s' — 매크로 때문일 수 있음" % n.type,
None,
",".join(_culprit_macros(text_lines, n.start_point[0]))))
elif n.is_error:
gaps.append(("parse_error", line,
"이 구간을 문법으로 해석하지 못함", None,
",".join(_culprit_macros(text_lines, n.start_point[0]))))
if n.type == "function_definition":
name, mangled = _ts_decl_name(n, src)
if name:
symbols.append((name, "function",
txt(n).split("{")[0].strip()[:120],
line, n.end_point[0] + 1, "tree-sitter"))
cur = name
if mangled:
gaps.append(("macro_mangled_decl", line,
"매크로가 시그니처를 가림 — 실제 이름이 다를 수 있음",
name,
",".join(_culprit_macros(text_lines,
n.start_point[0]))))
elif n.type in ("class_specifier", "struct_specifier", "enum_specifier",
"union_specifier"):
nm = n.child_by_field_name("name")
if nm is not None:
kind = {"class_specifier": "class", "struct_specifier": "struct",
"enum_specifier": "enum", "union_specifier": "union"}[n.type]
symbols.append((txt(nm), kind, txt(n).split("{")[0].strip()[:120],
line, n.end_point[0] + 1, "tree-sitter"))
# --- C 헤더의 실체는 '선언'이다. 정의만 뽑으면 헤더가 통째로 안 보인다.
elif n.type == "enumerator":
nm = n.child_by_field_name("name")
if nm is None:
nm = next((c for c in n.children if c.type == "identifier"), None)
if nm is not None:
symbols.append((txt(nm), "enum_constant", txt(n).strip()[:120],
line, n.end_point[0] + 1, "tree-sitter"))
elif n.type == "type_definition":
# typedef enum {...} a_e; / typedef unsigned int id_t;
# 이름은 마지막 직계 type_identifier 다 (앞쪽 것은 원본 타입 이름).
names = [c for c in n.children if c.type == "type_identifier"]
if names:
symbols.append((txt(names[-1]), "typedef",
txt(n).replace("\n", " ")[:120],
line, n.end_point[0] + 1, "tree-sitter"))
elif n.type == "preproc_def":
nm = n.child_by_field_name("name")
if nm is not None and txt(nm) not in guard_names:
symbols.append((txt(nm), "macro", txt(n).replace("\n", " ")[:120],
line, n.end_point[0] + 1, "tree-sitter"))
elif n.type == "preproc_function_def":
nm = n.child_by_field_name("name")
if nm is not None:
symbols.append((txt(nm), "macro_fn", txt(n).replace("\n", " ")[:120],
line, n.end_point[0] + 1, "tree-sitter"))
elif n.type == "declaration" and not in_func:
# 함수 밖에서만 기록한다. 안 그러면 지역변수가 전부 심볼이 되어
# 노이즈로 못 쓰게 된다.
d = n.child_by_field_name("declarator")
is_proto = False
probe = d
for _ in range(8):
if probe is None:
break
if probe.type == "function_declarator":
is_proto = True
break
probe = probe.child_by_field_name("declarator")
ident = _decl_ident(d) if d is not None else None
if ident is not None:
symbols.append((txt(ident),
"prototype" if is_proto else "variable",
txt(n).replace("\n", " ").strip()[:120],
line, n.end_point[0] + 1, "tree-sitter"))
elif n.type == "preproc_include":
p = n.child_by_field_name("path")
if p is not None:
edges.append((None, txt(p).strip('"<>'), None, "includes",
"tree-sitter", "confirmed"))
elif n.type == "call_expression":
fn = n.child_by_field_name("function")
if fn is not None and fn.type in _TS_NAME_NODES:
edges.append((enclosing, txt(fn), None, "calls",
"tree-sitter", "inferred"))
elif n.type == "initializer_list":
# 함수 포인터 테이블 — 초기화 리스트 안의 맨 식별자는 함수를
# 가리킬 수 있다. 호출로 안 잡히므로 구멍으로 남긴다.
for ch in n.children:
if ch.type == "identifier":
gaps.append(("fnptr_table", ch.start_point[0] + 1,
"%s — 테이블 등록. 호출로 잡히지 않음" % txt(ch),
None, None))
elif n.type == "preproc_arg":
if "##" in txt(n):
gaps.append(("token_paste", line,
"## 토큰 붙이기 — 생성되는 이름이 소스에 없음", None,
",".join(_culprit_macros(text_lines,
n.start_point[0]))))
elif n.type in ("preproc_ifdef", "preproc_if"):
# preproc_else/elif 는 기록하지 않는다 — 머리 노드 하나가
# 조건부 그룹 전체를 대표한다. 안 그러면 한 그룹이 2~3번 세어진다.
if _ts_is_include_guard(n, src):
gnm = n.child_by_field_name("name")
if gnm is not None:
guard_names.add(txt(gnm))
else:
cond = n.child_by_field_name("name")
gaps.append(("ifdef_branch", line,
"조건부 컴파일 %s — 어느 분기가 빌드되는지 알 수 없음"
% (txt(cond) if cond is not None else n.type),
None, None))
elif n.type in ("gnu_asm_expression", "asm_statement"):
gaps.append(("inline_asm", line, "인라인 asm — 해석 불가",
None, None))
child_in_func = in_func or n.type == "function_definition"
for ch in n.children:
walk(ch, cur, child_in_func)
walk(tree.root_node, None, False)
return symbols, edges, gaps
_LAST_GAPS = [] # 직전 parse_file 호출이 발견한 구멍. cmd_index 가 회수한다.
def parse_file(path: Path, lang: str, text: str, ignore_macros=()):
"""(symbols, edges) 반환. 구멍은 _LAST_GAPS 에 남긴다.
반환 시그니처를 바꾸지 않는 이유: cmd_doctor 등 기존 호출부를 깨지 않기 위함.
ignore_macros 도 같은 이유로 선택 인자다 (기본값 = 기존 동작).
"""
global _LAST_GAPS
_LAST_GAPS = []
if lang == "python":
return parse_python(path, text)
if lang in ("c", "cpp"):
text = blank_macros(text, ignore_macros)
r = parse_c_cpp_ts(path, text, lang)
# `.h` 는 C 일 수도 C++ 일 수도 있다. 확장자만 믿으면 C++ 헤더를
# C 문법으로 읽어 오류가 쏟아진다(실측: 사내 코드 .h 1,356개가 C++).
# C 로 읽어 오류가 났을 때만 C++ 로 다시 읽고, 더 나은 쪽을 택한다.
# `.c` 는 재시도하지 않는다 — 거기까지 추측하면 진짜 C 오류를 숨긴다.
if (r is not None and lang == "c"
and path.suffix.lower() in (".h", ".hxx", ".hh")):
n_err = sum(1 for g in r[2]
if g[0] in ("parse_error", "parse_missing"))
if n_err:
alt = parse_c_cpp_ts(path, text, "cpp")
if alt is not None:
alt_err = sum(1 for g in alt[2]
if g[0] in ("parse_error", "parse_missing"))
if alt_err < n_err:
r = alt
if r is not None:
symbols, edges, gaps = r
_LAST_GAPS = gaps
return symbols, edges
if has_universal_ctags(): # tree-sitter 없을 때만 폴백
r2 = parse_c_cpp_ctags(path, text)
if r2 is not None:
return r2
return parse_c_cpp(path, text)
if lang == "idl":
return parse_idl(path, text)
return [], []
# ---------------------------------------------------------------- index
def resolve_include(dst_name, files_by_name):
"""include/import 대상을 저장소 내 파일로 해석 시도. 실패 = 외부 의존."""
base = os.path.basename(dst_name)
cands = files_by_name.get(base, [])
if len(cands) == 1:
return cands[0]
for c in cands: # 경로 끝부분이 일치하면 채택
if c.endswith(dst_name):
return c
return None
def cmd_index(root: Path, only_files=None):
cfg = load_config(root)
con = open_db(root, create=True)
con.executescript(SCHEMA)
cur = con.cursor()
all_paths = [p for p in iter_source_files(root, cfg)]
files_by_name = {}
for p in all_paths:
rel = p.relative_to(root).as_posix()
files_by_name.setdefault(p.name, []).append(rel)
targets = all_paths
if only_files is not None:
wanted = set(only_files)
targets = [p for p in all_paths
if p.relative_to(root).as_posix() in wanted]
# 삭제된 파일 정리
for f in only_files:
if not (root / f).exists():
cur.execute("DELETE FROM symbols WHERE file_id IN "
"(SELECT id FROM files WHERE path=?)", (f,))
cur.execute("DELETE FROM edges WHERE src_file=?", (f,))
cur.execute("DELETE FROM gaps WHERE file=?", (f,))
cur.execute("DELETE FROM files WHERE path=?", (f,))
else:
cur.execute("DELETE FROM files")
cur.execute("DELETE FROM symbols")
cur.execute("DELETE FROM edges")
cur.execute("DELETE FROM gaps")
n_sym = n_edge = n_gap = 0
show_progress = sys.stderr.isatty() and len(targets) > 10
for i, p in enumerate(targets, 1):
rel = p.relative_to(root).as_posix()
if show_progress and (i % 10 == 0 or i == len(targets)):
print(f"\r색인 중... {i}/{len(targets)} {rel[:60]:<60}",
end="", file=sys.stderr, flush=True)
try:
raw, text, _enc = read_source(p)
except Exception:
continue
lang = LANG_BY_EXT[p.suffix.lower()]
sha = sha_of(raw)
loc = text.count("\n") + 1
cur.execute("DELETE FROM symbols WHERE file_id IN "
"(SELECT id FROM files WHERE path=?)", (rel,))
cur.execute("DELETE FROM edges WHERE src_file=?", (rel,))
cur.execute("DELETE FROM gaps WHERE file=?", (rel,))
cur.execute("DELETE FROM files WHERE path=?", (rel,))
cur.execute("INSERT INTO files(path, sha, lang, loc) VALUES(?,?,?,?)",
(rel, sha, lang, loc))
fid = cur.lastrowid
symbols, edges = parse_file(p, lang, text,
cfg.get("ignore_macros", []))
for (name, kind, sig, ls, le, prov) in symbols:
cur.execute("INSERT INTO symbols(file_id,name,kind,signature,"
"line_start,line_end,provenance) VALUES(?,?,?,?,?,?,?)",
(fid, name, kind, sig, ls, le, prov))
n_sym += 1
for (src_sym, dst_name, _dst_file, kind, prov, conf) in edges:
dst_file = None
if kind in ("includes", "imports"):
probe = dst_name.replace(".", "/") + ".py" \
if kind == "imports" else dst_name
dst_file = resolve_include(probe, files_by_name)