vcode-analysis 0.5.3__py3-none-any.whl → 0.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,10 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import re
7
+ import subprocess
8
+ import sys
9
+ import threading
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
11
  from dataclasses import dataclass, field
8
12
  from pathlib import Path
9
13
  from typing import TYPE_CHECKING
@@ -125,10 +129,16 @@ class KnowledgeGraph:
125
129
  rel_type_counts[r.type] = rel_type_counts.get(r.type, 0) + 1
126
130
  lines.append("## 关系统计\n")
127
131
  lines.append(f"- 总计: {len(self.relations)} 条关系\n")
132
+ max_count = max(rel_type_counts.values()) if rel_type_counts else 1
128
133
  for t, c in sorted(rel_type_counts.items(), key=lambda x: -x[1]):
129
- lines.append(f"- {t}: {c}")
134
+ bar_len = int(c / max_count * 20)
135
+ bar = "█" * bar_len + "░" * (20 - bar_len)
136
+ lines.append(f"- {t}: {c} {bar}")
130
137
  lines.append("")
131
138
 
139
+ # 架构洞察
140
+ lines.extend(self._markdown_architecture_insights())
141
+
132
142
  # 实体列表
133
143
  lines.append("## 实体列表\n")
134
144
  for e in sorted(self.entities, key=lambda x: (x.type, x.id)):
@@ -157,6 +167,375 @@ class KnowledgeGraph:
157
167
 
158
168
  return "\n".join(lines)
159
169
 
170
+ def _markdown_architecture_insights(self) -> list[str]:
171
+ """生成架构洞察视图"""
172
+ lines = ["## 架构洞察\n"]
173
+
174
+ entity_map = {e.id: e for e in self.entities}
175
+ modules = [e for e in self.entities if e.type == "module"]
176
+
177
+ # 模块依赖矩阵
178
+ lines.append("### 模块依赖矩阵\n")
179
+ module_ids = [m.id for m in modules]
180
+ # 只取顶层模块(取前3段作为模块组)
181
+ top_modules: dict[str, set[str]] = {}
182
+ for m in modules:
183
+ parts = m.id.split(".")
184
+ top = parts[0] if parts else m.id
185
+ if len(parts) > 1:
186
+ top = f"{parts[0]}.{parts[1]}"
187
+ top_modules.setdefault(top, set()).add(m.id)
188
+
189
+ top_names = sorted(top_modules.keys())[:15]
190
+ if len(top_names) >= 2:
191
+ import_rels = [r for r in self.relations if r.type == "imports"]
192
+ dep_matrix: dict[str, dict[str, int]] = {n: {} for n in top_names}
193
+ for r in import_rels:
194
+ src_top = None
195
+ tgt_top = None
196
+ for tn in top_names:
197
+ if r.source_id.startswith(tn):
198
+ src_top = tn
199
+ if r.target_id.startswith(tn):
200
+ tgt_top = tn
201
+ if src_top and tgt_top and src_top != tgt_top:
202
+ dep_matrix[src_top][tgt_top] = dep_matrix[src_top].get(tgt_top, 0) + 1
203
+
204
+ # 表头
205
+ short_names = [n.split(".")[-1][:12] for n in top_names]
206
+ header = "| 从 ↓ → 到 | " + " | ".join(short_names) + " |"
207
+ lines.append(header)
208
+ lines.append("|" + "|".join(["---"] * (len(top_names) + 1)) + "|")
209
+ for i, src in enumerate(top_names):
210
+ row = f"| {short_names[i]} |"
211
+ for tgt in top_names:
212
+ count = dep_matrix[src].get(tgt, 0)
213
+ row += f" {count or ''} |"
214
+ lines.append(row)
215
+ lines.append("")
216
+
217
+ # 依赖热点 TOP 10
218
+ lines.append("### 依赖热点 TOP 10\n")
219
+ incoming: dict[str, int] = {}
220
+ for r in self.relations:
221
+ if r.type in ("imports", "depends_on", "calls", "inherits", "implements"):
222
+ incoming[r.target_id] = incoming.get(r.target_id, 0) + 1
223
+ entity_name_map = {e.id: e.name for e in self.entities}
224
+ hotspots = sorted(incoming.items(), key=lambda x: -x[1])[:10]
225
+ if hotspots:
226
+ for eid, count in hotspots:
227
+ name = entity_name_map.get(eid, eid)
228
+ lines.append(f"- `{name}` — 被依赖 {count} 次")
229
+ else:
230
+ lines.append("- 无显著依赖热点")
231
+ lines.append("")
232
+
233
+ # 孤立实体
234
+ related_ids: set[str] = set()
235
+ for r in self.relations:
236
+ related_ids.add(r.source_id)
237
+ related_ids.add(r.target_id)
238
+ orphans = [e for e in self.entities if e.type not in ("module",) and e.id not in related_ids]
239
+ if orphans:
240
+ lines.append(f"### 孤立实体 ({len(orphans)})\n")
241
+ for o in orphans[:20]:
242
+ lines.append(f"- **[{o.type}]** `{o.name}` — {o.file_path}")
243
+ if len(orphans) > 20:
244
+ lines.append(f"- ... 还有 {len(orphans) - 20} 个")
245
+ lines.append("")
246
+
247
+ return lines
248
+
249
+ def to_html(self) -> str:
250
+ """生成交互式 HTML 可视化(ECharts 力导向图)"""
251
+ # 构建节点和边数据
252
+ nodes = []
253
+ type_colors = {
254
+ "module": "#5470c6", "class": "#91cc75", "interface": "#fac858",
255
+ "function": "#ee6666", "variable": "#73c0de", "enum": "#3ba272",
256
+ }
257
+ for e in self.entities:
258
+ nodes.append({
259
+ "id": e.id, "name": e.name, "type": e.type,
260
+ "file_path": e.file_path, "line": e.line,
261
+ "symbolSize": min(60, max(15, 15 + len([r for r in self.relations if r.source_id == e.id or r.target_id == e.id]) * 3)),
262
+ "itemStyle": {"color": type_colors.get(e.type, "#999")},
263
+ "category": e.type,
264
+ })
265
+
266
+ edges = []
267
+ rel_colors = {
268
+ "contains": "#ccc", "imports": "#5470c6", "calls": "#ee6666",
269
+ "inherits": "#91cc75", "implements": "#fac858", "depends_on": "#73c0de",
270
+ }
271
+ for r in self.relations:
272
+ edges.append({
273
+ "source": r.source_id, "target": r.target_id,
274
+ "type": r.type,
275
+ "lineStyle": {"color": rel_colors.get(r.type, "#999"), "width": 1.5},
276
+ })
277
+
278
+ categories = [
279
+ {"name": t, "itemStyle": {"color": c}}
280
+ for t, c in type_colors.items()
281
+ if any(e.type == t for e in self.entities)
282
+ ]
283
+
284
+ # 业务规则数据
285
+ rules_data = []
286
+ for br in self.business_rules:
287
+ rules_data.append({
288
+ "id": br.id, "description": br.description,
289
+ "category": br.category, "entities": br.entities[:5],
290
+ })
291
+
292
+ # 统计数据
293
+ type_counts = {}
294
+ for e in self.entities:
295
+ type_counts[e.type] = type_counts.get(e.type, 0) + 1
296
+ rel_type_counts = {}
297
+ for r in self.relations:
298
+ rel_type_counts[r.type] = rel_type_counts.get(r.type, 0) + 1
299
+
300
+ nodes_json = json.dumps(nodes, ensure_ascii=False)
301
+ edges_json = json.dumps(edges, ensure_ascii=False)
302
+ categories_json = json.dumps(categories, ensure_ascii=False)
303
+ rules_json = json.dumps(rules_data, ensure_ascii=False)
304
+ type_counts_json = json.dumps(type_counts, ensure_ascii=False)
305
+ rel_counts_json = json.dumps(rel_type_counts, ensure_ascii=False)
306
+ meta_json = json.dumps(self.metadata, ensure_ascii=False)
307
+
308
+ return f"""<!DOCTYPE html>
309
+ <html lang="zh-CN">
310
+ <head>
311
+ <meta charset="UTF-8">
312
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
313
+ <title>代码知识图谱</title>
314
+ <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
315
+ <style>
316
+ * {{ margin: 0; padding: 0; box-sizing: border-box; }}
317
+ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; color: #333; }}
318
+ .header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px 30px; }}
319
+ .header h1 {{ font-size: 24px; margin-bottom: 8px; }}
320
+ .header .meta {{ font-size: 13px; opacity: 0.85; }}
321
+ .container {{ display: flex; height: calc(100vh - 80px); }}
322
+ .sidebar {{ width: 320px; background: white; border-right: 1px solid #e0e0e0; overflow-y: auto; padding: 16px; }}
323
+ .main {{ flex: 1; position: relative; }}
324
+ #graph {{ width: 100%; height: 100%; }}
325
+ .section {{ margin-bottom: 16px; }}
326
+ .section h3 {{ font-size: 14px; color: #666; margin-bottom: 8px; border-bottom: 1px solid #eee; padding-bottom: 4px; }}
327
+ .stat-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }}
328
+ .stat-card {{ background: #f8f9fa; border-radius: 6px; padding: 8px 12px; }}
329
+ .stat-card .num {{ font-size: 20px; font-weight: 700; color: #333; }}
330
+ .stat-card .label {{ font-size: 11px; color: #999; }}
331
+ .filter-group {{ display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 8px; }}
332
+ .filter-btn {{ padding: 3px 10px; border-radius: 12px; border: 1px solid #ddd; background: white; font-size: 12px; cursor: pointer; transition: all 0.2s; }}
333
+ .filter-btn.active {{ background: #667eea; color: white; border-color: #667eea; }}
334
+ .filter-btn:hover {{ border-color: #667eea; }}
335
+ .rule-item {{ padding: 6px 8px; margin-bottom: 4px; border-radius: 4px; font-size: 12px; background: #f8f9fa; }}
336
+ .rule-item.architecture {{ border-left: 3px solid #ee6666; }}
337
+ .rule-item.naming {{ border-left: 3px solid #fac858; }}
338
+ .rule-item.pattern {{ border-left: 3px solid #91cc75; }}
339
+ .rule-item.constraint {{ border-left: 3px solid #5470c6; }}
340
+ .detail-panel {{ position: absolute; right: 16px; top: 16px; width: 280px; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.15); padding: 16px; display: none; z-index: 10; }}
341
+ .detail-panel h4 {{ font-size: 15px; margin-bottom: 8px; }}
342
+ .detail-panel .field {{ font-size: 12px; color: #666; margin-bottom: 4px; }}
343
+ .detail-panel .field span {{ color: #333; font-weight: 500; }}
344
+ .rel-type-legend {{ display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }}
345
+ .legend-item {{ display: flex; align-items: center; gap: 4px; font-size: 11px; }}
346
+ .legend-dot {{ width: 10px; height: 3px; border-radius: 1px; }}
347
+ </style>
348
+ </head>
349
+ <body>
350
+ <div class="header">
351
+ <h1>代码知识图谱</h1>
352
+ <div class="meta" id="headerMeta"></div>
353
+ </div>
354
+ <div class="container">
355
+ <div class="sidebar">
356
+ <div class="section">
357
+ <h3>统计概览</h3>
358
+ <div class="stat-grid" id="statsGrid"></div>
359
+ </div>
360
+ <div class="section">
361
+ <h3>实体类型筛选</h3>
362
+ <div class="filter-group" id="entityFilters"></div>
363
+ </div>
364
+ <div class="section">
365
+ <h3>关系类型筛选</h3>
366
+ <div class="filter-group" id="relFilters"></div>
367
+ <div class="rel-type-legend" id="relLegend"></div>
368
+ </div>
369
+ <div class="section">
370
+ <h3>业务规则</h3>
371
+ <div id="rulesList"></div>
372
+ </div>
373
+ </div>
374
+ <div class="main">
375
+ <div id="graph"></div>
376
+ <div class="detail-panel" id="detailPanel">
377
+ <h4 id="detailName"></h4>
378
+ <div id="detailContent"></div>
379
+ </div>
380
+ </div>
381
+ </div>
382
+ <script>
383
+ (function() {{
384
+ const nodes = {nodes_json};
385
+ const edges = {edges_json};
386
+ const categories = {categories_json};
387
+ const rules = {rules_json};
388
+ const typeCounts = {type_counts_json};
389
+ const relCounts = {rel_counts_json};
390
+ const metadata = {meta_json};
391
+
392
+ // Header
393
+ const metaEl = document.getElementById('headerMeta');
394
+ metaEl.textContent = Object.entries(metadata).map(([k,v]) => k + ': ' + v).join(' | ');
395
+
396
+ // Stats
397
+ const statsGrid = document.getElementById('statsGrid');
398
+ statsGrid.innerHTML = Object.entries({{'实体总数': Object.values(typeCounts).reduce((a,b)=>a+b,0), '关系总数': Object.values(relCounts).reduce((a,b)=>a+b,0), ...typeCounts, ...relCounts}}).slice(0,8).map(([k,v]) => '<div class="stat-card"><div class="num">'+v+'</div><div class="label">'+k+'</div></div>').join('');
399
+
400
+ // Entity filters
401
+ const entityFilters = document.getElementById('entityFilters');
402
+ const activeTypes = new Set(Object.keys(typeCounts));
403
+ Object.keys(typeCounts).forEach(t => {{
404
+ const btn = document.createElement('button');
405
+ btn.className = 'filter-btn active';
406
+ btn.textContent = t + ' (' + typeCounts[t] + ')';
407
+ btn.dataset.type = t;
408
+ btn.onclick = () => {{
409
+ if (activeTypes.has(t)) {{ activeTypes.delete(t); btn.classList.remove('active'); }}
410
+ else {{ activeTypes.add(t); btn.classList.add('active'); }}
411
+ updateGraph();
412
+ }};
413
+ entityFilters.appendChild(btn);
414
+ }});
415
+
416
+ // Relation filters
417
+ const relFilters = document.getElementById('relFilters');
418
+ const activeRels = new Set(Object.keys(relCounts));
419
+ const relColors = {{"contains": "#ccc", "imports": "#5470c6", "calls": "#ee6666", "inherits": "#91cc75", "implements": "#fac858", "depends_on": "#73c0de"}};
420
+ Object.keys(relCounts).forEach(t => {{
421
+ const btn = document.createElement('button');
422
+ btn.className = 'filter-btn active';
423
+ btn.textContent = t + ' (' + relCounts[t] + ')';
424
+ btn.dataset.type = t;
425
+ btn.onclick = () => {{
426
+ if (activeRels.has(t)) {{ activeRels.delete(t); btn.classList.remove('active'); }}
427
+ else {{ activeRels.add(t); btn.classList.add('active'); }}
428
+ updateGraph();
429
+ }};
430
+ relFilters.appendChild(btn);
431
+ }});
432
+
433
+ // Legend
434
+ const relLegend = document.getElementById('relLegend');
435
+ Object.entries(relColors).forEach(([t, c]) => {{
436
+ if (relCounts[t]) {{
437
+ relLegend.innerHTML += '<div class="legend-item"><div class="legend-dot" style="background:'+c+'"></div>'+t+'</div>';
438
+ }}
439
+ }});
440
+
441
+ // Rules
442
+ const rulesList = document.getElementById('rulesList');
443
+ rules.forEach(r => {{
444
+ rulesList.innerHTML += '<div class="rule-item '+r.category+'"><strong>['+r.category+']</strong> '+r.description+'</div>';
445
+ }});
446
+
447
+ // ECharts
448
+ const chart = echarts.init(document.getElementById('graph'));
449
+ const nodeMap = {{}};
450
+ nodes.forEach(n => nodeMap[n.id] = n);
451
+
452
+ function updateGraph() {{
453
+ const filteredNodes = nodes.filter(n => activeTypes.has(n.type));
454
+ const nodeIds = new Set(filteredNodes.map(n => n.id));
455
+ const filteredEdges = edges.filter(e => nodeIds.has(e.source) && nodeIds.has(e.target) && activeRels.has(e.type));
456
+
457
+ chart.setOption({{
458
+ tooltip: {{
459
+ formatter: function(p) {{
460
+ if (p.dataType === 'node') {{
461
+ return '<b>'+p.name+'</b><br/>类型: '+p.data.type+'<br/>文件: '+p.data.file_path+(p.data.line?':'+p.data.line:'');
462
+ }}
463
+ return p.data.type + ': ' + p.data.source + ' → ' + p.data.target;
464
+ }}
465
+ }},
466
+ legend: {{ data: categories.map(c => c.name), bottom: 10 }},
467
+ series: [{{
468
+ type: 'graph', layout: 'force', roam: true, draggable: true,
469
+ data: filteredNodes, links: filteredEdges, categories: categories,
470
+ force: {{ repulsion: 300, gravity: 0.1, edgeLength: [80, 200], layoutAnimation: true }},
471
+ label: {{ show: true, position: 'right', fontSize: 10, formatter: '{{b}}' }},
472
+ emphasis: {{ focus: 'adjacency', lineStyle: {{ width: 3 }} }},
473
+ edgeLabel: {{ show: false }},
474
+ scaleLimit: {{ min: 0.3, max: 3 }},
475
+ }}]
476
+ }}, true);
477
+ }}
478
+
479
+ updateGraph();
480
+
481
+ chart.on('click', function(params) {{
482
+ const panel = document.getElementById('detailPanel');
483
+ if (params.dataType === 'node') {{
484
+ const n = params.data;
485
+ document.getElementById('detailName').textContent = n.name;
486
+ let html = '<div class="field">类型: <span>'+n.type+'</span></div>';
487
+ html += '<div class="field">文件: <span>'+n.file_path+(n.line?':'+n.line:'')+'</span></div>';
488
+ html += '<div class="field">ID: <span style="font-size:10px;word-break:break-all;">'+n.id+'</span></div>';
489
+ // 显示相关关系
490
+ const rels = edges.filter(e => e.source === n.id || e.target === n.id);
491
+ if (rels.length > 0) {{
492
+ html += '<div class="field" style="margin-top:8px;">关系 ('+rels.length+'):</div>';
493
+ rels.slice(0, 15).forEach(r => {{
494
+ const dir = r.source === n.id ? '→' : '←';
495
+ const other = r.source === n.id ? r.target : r.source;
496
+ const otherName = nodeMap[other] ? nodeMap[other].name : other;
497
+ html += '<div class="field" style="padding-left:8px;">'+dir+' ['+r.type+'] '+otherName+'</div>';
498
+ }});
499
+ if (rels.length > 15) html += '<div class="field">... 还有 '+(rels.length-15)+' 条</div>';
500
+ }}
501
+ document.getElementById('detailContent').innerHTML = html;
502
+ panel.style.display = 'block';
503
+ }} else {{
504
+ panel.style.display = 'none';
505
+ }}
506
+ }});
507
+
508
+ window.addEventListener('resize', () => chart.resize());
509
+ }})();
510
+ </script>
511
+ </body>
512
+ </html>"""
513
+
514
+
515
+ def _parse_in_subprocess(file_path: str, code: str, timeout: int = 10):
516
+ """在子进程中解析文件,超时则终止(防止解析器卡死)"""
517
+ try:
518
+ result = subprocess.run(
519
+ [sys.executable, "-c", (
520
+ "import sys, json, pickle, base64; "
521
+ "from parsers import get_parser_for_file; "
522
+ "code = sys.stdin.buffer.read().decode('utf-8', errors='ignore'); "
523
+ "parser = get_parser_for_file(sys.argv[1]); "
524
+ "r = parser.parse_code(code, sys.argv[1]) if parser else None; "
525
+ "data = base64.b64encode(pickle.dumps(r)).decode() if r else ''; "
526
+ "print(data)"
527
+ ), file_path],
528
+ input=code.encode("utf-8"),
529
+ capture_output=True,
530
+ timeout=timeout,
531
+ )
532
+ if result.returncode != 0 or not result.stdout.strip():
533
+ return None
534
+ import pickle, base64
535
+ return pickle.loads(base64.b64decode(result.stdout.strip()))
536
+ except (subprocess.TimeoutExpired, Exception):
537
+ return None
538
+
160
539
 
161
540
  # ── 分析器 ──────────────────────────────────────────────
162
541
 
@@ -164,8 +543,11 @@ class KnowledgeGraph:
164
543
  class KnowledgeGraphAnalyzer:
165
544
  """知识图谱分析器 — 从代码库自动构建领域模型图谱"""
166
545
 
167
- def __init__(self, analyzer: Analyzer):
546
+ def __init__(self, analyzer: Analyzer, log_callback=None, workers: int = 1, max_file_size: int = 500_000):
168
547
  self.analyzer = analyzer
548
+ self._log = log_callback or (lambda msg, level="INFO": None)
549
+ self.workers = max(1, workers)
550
+ self.max_file_size = max_file_size # 超过此大小的文件跳过解析
169
551
 
170
552
  def analyze(self, target_path: str, use_llm: bool = False) -> KnowledgeGraph:
171
553
  """分析目标路径,构建知识图谱"""
@@ -174,16 +556,30 @@ class KnowledgeGraphAnalyzer:
174
556
  raise FileNotFoundError(f"目标路径不存在: {target_path}")
175
557
 
176
558
  # 扫描文件
559
+ self._log("扫描文件...", "DEBUG")
177
560
  file_infos = list(self.analyzer.scan_files(str(target)))
178
561
  if not file_infos:
179
562
  return KnowledgeGraph(metadata={"target_path": str(target), "file_count": 0})
563
+ self._log(f"发现 {len(file_infos)} 个文件", "OK")
564
+
565
+ # 一次性解析所有文件,缓存结果
566
+ self._log("解析代码结构...", "DEBUG")
567
+ parse_cache = self._parse_all_files(file_infos)
568
+ self._log(f"成功解析 {len(parse_cache)} 个文件", "OK")
180
569
 
181
- # 提取实体和关系
182
- entities = self._extract_entities(file_infos)
183
- relations = self._extract_relations(entities, file_infos)
570
+ # 提取实体和关系(共享 parse_cache)
571
+ self._log("提取实体...", "DEBUG")
572
+ entities = self._extract_entities(file_infos, parse_cache)
573
+ self._log(f"提取 {len(entities)} 个实体", "OK")
574
+
575
+ self._log("提取关系...", "DEBUG")
576
+ relations = self._extract_relations(entities, parse_cache)
577
+ self._log(f"提取 {len(relations)} 条关系", "OK")
184
578
 
185
579
  # 检测业务规则
580
+ self._log("检测业务规则...", "DEBUG")
186
581
  business_rules = self._detect_business_rules(entities, relations)
582
+ self._log(f"检测 {len(business_rules)} 条规则", "OK")
187
583
 
188
584
  kg = KnowledgeGraph(
189
585
  entities=entities,
@@ -200,20 +596,180 @@ class KnowledgeGraphAnalyzer:
200
596
 
201
597
  # 可选 LLM 增强
202
598
  if use_llm:
599
+ self._log("LLM 增强分析...", "DEBUG")
203
600
  kg = self._enhance_with_llm(kg)
601
+ self._log("LLM 增强完成", "OK")
204
602
 
205
603
  return kg
206
604
 
207
- def _extract_entities(self, file_infos: list) -> list[KGEntity]:
208
- """从文件列表中提取所有实体"""
605
+ def _parse_all_files(self, file_infos: list) -> dict[str, tuple]:
606
+ """解析所有文件,返回 {file_path: (module_id, parse_result)} 缓存。支持并发。"""
607
+ # 先筛选出有对应解析器的代码文件
608
+ code_files = []
609
+ skipped_size = 0
610
+ for fi in file_infos:
611
+ file_path = fi.relative_path if hasattr(fi, "relative_path") else str(fi)
612
+ if get_parser_for_file(file_path) is not None:
613
+ abs_path = str(fi.path) if hasattr(fi, "path") else file_path
614
+ try:
615
+ size = Path(abs_path).stat().st_size
616
+ except OSError:
617
+ continue
618
+ if size > self.max_file_size:
619
+ skipped_size += 1
620
+ continue
621
+ code_files.append(fi)
622
+
623
+ total = len(code_files)
624
+ skipped = len(file_infos) - total
625
+ if skipped:
626
+ self._log(f"跳过 {skipped} 个非代码文件,解析 {total} 个代码文件")
627
+ if skipped_size:
628
+ self._log(f"跳过 {skipped_size} 个超大文件 (>{self.max_file_size//1024}KB)")
629
+ parsed_count = 0
630
+ parsed_lock = threading.Lock()
631
+ last_reported_pct = -1
632
+
633
+ def _report_progress():
634
+ nonlocal last_reported_pct
635
+ pct = int(parsed_count / total * 100) if total > 0 else 100
636
+ if pct >= last_reported_pct + 10 or parsed_count == total:
637
+ last_reported_pct = pct
638
+ self._log(f"解析进度: {parsed_count}/{total} ({pct}%)")
639
+
640
+ def _parse_one(fi) -> Optional[tuple[str, str, object]]:
641
+ nonlocal parsed_count
642
+ file_path = fi.relative_path if hasattr(fi, "relative_path") else str(fi)
643
+ abs_path = str(fi.path) if hasattr(fi, "path") else file_path
644
+ self._log(f"解析: {file_path}", "DEBUG")
645
+ try:
646
+ code = Path(abs_path).read_text(encoding="utf-8", errors="ignore")
647
+ parser = get_parser_for_file(file_path)
648
+ # TS/TSX 解析器可能卡死,使用子进程超时保护
649
+ ext = Path(file_path).suffix.lower()
650
+ if ext in (".ts", ".tsx", ".mts", ".cts") and parser is not None:
651
+ result = _parse_in_subprocess(file_path, code, timeout=10)
652
+ if result is None:
653
+ self._log(f"解析超时(10s),跳过: {file_path}", "WARN")
654
+ with parsed_lock:
655
+ parsed_count += 1
656
+ _report_progress()
657
+ return None
658
+ else:
659
+ result = parser.parse_code(code, file_path)
660
+ module_id = self._file_to_module_id(file_path)
661
+ with parsed_lock:
662
+ parsed_count += 1
663
+ _report_progress()
664
+ return (file_path, module_id, result)
665
+ except Exception as e:
666
+ self._log(f"解析失败: {file_path} ({e})", "WARN")
667
+ with parsed_lock:
668
+ parsed_count += 1
669
+ _report_progress()
670
+ return None
671
+
672
+ cache = {}
673
+ if total == 0:
674
+ return cache
675
+
676
+ effective_workers = self.workers if self.workers > 1 else 1
677
+ with ThreadPoolExecutor(max_workers=effective_workers) as executor:
678
+ futures = {executor.submit(_parse_one, fi): fi for fi in code_files}
679
+ for future in as_completed(futures):
680
+ try:
681
+ r = future.result()
682
+ except Exception:
683
+ continue
684
+ if r:
685
+ cache[r[0]] = (r[1], r[2])
686
+ return cache
687
+
688
+ # ── 语言感知字段映射 ────────────────────────────────────
689
+
690
+ @staticmethod
691
+ def _detect_language(file_path: str) -> str:
692
+ ext = Path(file_path).suffix.lower()
693
+ mapping = {
694
+ ".py": "python", ".kt": "kotlin", ".kts": "kotlin",
695
+ ".java": "java", ".js": "javascript", ".jsx": "javascript",
696
+ ".ts": "typescript", ".tsx": "typescript", ".mts": "typescript",
697
+ ".c": "c", ".h": "c", ".cpp": "c", ".hpp": "c",
698
+ }
699
+ return mapping.get(ext, "unknown")
700
+
701
+ @staticmethod
702
+ def _extract_class_bases(cls_obj, language: str) -> list[str]:
703
+ """语言感知的基类/接口提取"""
704
+ if language == "kotlin":
705
+ bases = []
706
+ extends = getattr(cls_obj, "extends", None)
707
+ if extends:
708
+ bases.append(extends)
709
+ bases.extend(getattr(cls_obj, "implements", []) or [])
710
+ return bases
711
+ # Python/Java/JS/TS 都用 bases 字段
712
+ return getattr(cls_obj, "bases", []) or []
713
+
714
+ @staticmethod
715
+ def _extract_class_type(cls_obj, language: str) -> str:
716
+ """语言感知的类类型提取,映射到 KG 实体类型"""
717
+ if language == "kotlin":
718
+ class_type = getattr(cls_obj, "class_type", "class") or "class"
719
+ type_map = {
720
+ "interface": "interface", "object": "class",
721
+ "enum class": "class", "sealed class": "class",
722
+ "data class": "class", "value class": "class",
723
+ }
724
+ return type_map.get(class_type, "class")
725
+ return "class"
726
+
727
+ @staticmethod
728
+ def _extract_class_methods(cls_obj, language: str) -> list:
729
+ """语言感知的方法提取"""
730
+ methods = getattr(cls_obj, "methods", [])
731
+ if methods:
732
+ return methods
733
+ # Kotlin: functions 字段
734
+ if language == "kotlin":
735
+ return getattr(cls_obj, "functions", []) or []
736
+ return []
737
+
738
+ @staticmethod
739
+ def _extract_method_params(method_obj, language: str) -> list[str]:
740
+ """语言感知的方法参数提取"""
741
+ # Python: args 字段
742
+ params = getattr(method_obj, "args", None)
743
+ if params is not None:
744
+ return [str(p) for p in params]
745
+ # Kotlin/Java: parameters 字段(可能是 dict 列表)
746
+ params = getattr(method_obj, "parameters", None)
747
+ if params is not None:
748
+ return [str(p.get("name", p) if isinstance(p, dict) else p) for p in params]
749
+ # fallback: params 字段
750
+ params = getattr(method_obj, "params", None)
751
+ if params is not None:
752
+ return [str(p) for p in params]
753
+ return []
754
+
755
+ @staticmethod
756
+ def _extract_import_module(imp_obj, language: str) -> str:
757
+ """语言感知的导入模块名提取"""
758
+ # Kotlin: path 字段
759
+ if language == "kotlin":
760
+ return getattr(imp_obj, "path", "") or ""
761
+ # Python/Java/JS: module 字段
762
+ return getattr(imp_obj, "module", None) or getattr(imp_obj, "source", None) or ""
763
+
764
+ def _extract_entities(self, file_infos: list, parse_cache: dict) -> list[KGEntity]:
765
+ """从解析结果中提取实体"""
209
766
  entities = []
210
767
  entity_id_set: set[str] = set()
211
768
 
212
769
  for fi in file_infos:
213
- # FileInfo 对象有 relative_path 和 path 属性
214
770
  file_path = fi.relative_path if hasattr(fi, "relative_path") else str(fi)
215
- abs_path = str(fi.path) if hasattr(fi, "path") else file_path
216
771
  module_id = self._file_to_module_id(file_path)
772
+ language = self._detect_language(file_path)
217
773
 
218
774
  # 模块实体
219
775
  module_entity = KGEntity(
@@ -225,42 +781,44 @@ class KnowledgeGraphAnalyzer:
225
781
  entities.append(module_entity)
226
782
  entity_id_set.add(module_id)
227
783
 
228
- # 使用解析器提取类和函数
229
- parser = get_parser_for_file(file_path)
230
- if parser is None:
231
- continue
232
-
233
- try:
234
- code = Path(abs_path).read_text(encoding="utf-8", errors="ignore")
235
- result = parser.parse_code(code, file_path)
236
- except Exception:
784
+ # 从缓存获取解析结果
785
+ cached = parse_cache.get(file_path)
786
+ if cached is None:
237
787
  continue
788
+ _, result = cached
238
789
 
239
790
  # 类实体
240
791
  for cls in getattr(result, "classes", []):
241
- cls_id = f"{module_id}.{cls.name}"
792
+ cls_name = cls.name
793
+ if not cls_name or cls_name == "Unknown":
794
+ continue # 跳过解析失败的类
795
+ cls_id = f"{module_id}.{cls_name}"
242
796
  if cls_id in entity_id_set:
243
797
  cls_id = f"{cls_id}@{file_path}:{getattr(cls, 'line_start', 0)}"
244
798
  entity_id_set.add(cls_id)
245
799
 
800
+ entity_type = self._extract_class_type(cls, language)
801
+ bases = self._extract_class_bases(cls, language)
802
+ methods = self._extract_class_methods(cls, language)
803
+
246
804
  cls_entity = KGEntity(
247
805
  id=cls_id,
248
- name=cls.name,
249
- type="class",
806
+ name=cls_name,
807
+ type=entity_type,
250
808
  file_path=file_path,
251
809
  line=getattr(cls, "line_start", 0),
252
810
  metadata={
253
- "bases": getattr(cls, "bases", []),
254
- "methods": [m.name for m in getattr(cls, "methods", [])],
811
+ "bases": bases,
812
+ "methods": [m.name for m in methods if hasattr(m, "name")],
255
813
  "docstring": getattr(cls, "docstring", None),
256
814
  },
257
815
  )
258
816
  entities.append(cls_entity)
259
817
 
260
- # 类包含方法 → contains 关系(在 _extract_relations 中处理)
261
818
  # 方法实体
262
- for m in getattr(cls, "methods", []):
263
- method_id = f"{cls_id}.{m.name}"
819
+ for m in methods:
820
+ m_name = m.name if hasattr(m, "name") else str(m)
821
+ method_id = f"{cls_id}.{m_name}"
264
822
  if method_id in entity_id_set:
265
823
  method_id = f"{method_id}@{file_path}:{getattr(m, 'line_start', 0)}"
266
824
  entity_id_set.add(method_id)
@@ -268,12 +826,12 @@ class KnowledgeGraphAnalyzer:
268
826
  entities.append(
269
827
  KGEntity(
270
828
  id=method_id,
271
- name=m.name,
829
+ name=m_name,
272
830
  type="function",
273
831
  file_path=file_path,
274
832
  line=getattr(m, "line_start", 0),
275
833
  metadata={
276
- "params": [str(p) for p in getattr(m, "params", getattr(m, "args", []))],
834
+ "params": self._extract_method_params(m, language),
277
835
  "decorators": getattr(m, "decorators", []),
278
836
  },
279
837
  )
@@ -281,7 +839,8 @@ class KnowledgeGraphAnalyzer:
281
839
 
282
840
  # 函数实体(模块级)
283
841
  for func in getattr(result, "functions", []):
284
- func_id = f"{module_id}.{func.name}"
842
+ func_name = func.name if hasattr(func, "name") else str(func)
843
+ func_id = f"{module_id}.{func_name}"
285
844
  if func_id in entity_id_set:
286
845
  func_id = f"{func_id}@{file_path}:{getattr(func, 'line_start', 0)}"
287
846
  entity_id_set.add(func_id)
@@ -289,12 +848,12 @@ class KnowledgeGraphAnalyzer:
289
848
  entities.append(
290
849
  KGEntity(
291
850
  id=func_id,
292
- name=func.name,
851
+ name=func_name,
293
852
  type="function",
294
853
  file_path=file_path,
295
854
  line=getattr(func, "line_start", 0),
296
855
  metadata={
297
- "params": [str(p) for p in getattr(func, "params", getattr(func, "args", []))],
856
+ "params": self._extract_method_params(func, language),
298
857
  "decorators": getattr(func, "decorators", []),
299
858
  "return_type": getattr(func, "return_type", getattr(func, "returns", None)),
300
859
  },
@@ -303,8 +862,8 @@ class KnowledgeGraphAnalyzer:
303
862
 
304
863
  return entities
305
864
 
306
- def _extract_relations(self, entities: list[KGEntity], file_infos: list) -> list[KGRelation]:
307
- """从实体和文件信息中提取关系"""
865
+ def _extract_relations(self, entities: list[KGEntity], parse_cache: dict) -> list[KGRelation]:
866
+ """从实体和解析缓存中提取关系"""
308
867
  relations = []
309
868
  entity_map = {e.id: e for e in entities}
310
869
 
@@ -313,9 +872,8 @@ class KnowledgeGraphAnalyzer:
313
872
  for mod in modules:
314
873
  mod_prefix = mod.id + "."
315
874
  for e in entities:
316
- if e.type in ("class", "function") and e.id.startswith(mod_prefix):
317
- # 确保是直接子级(非嵌套方法)
318
- remainder = e.id[len(mod_prefix) :]
875
+ if e.type in ("class", "function", "interface") and e.id.startswith(mod_prefix):
876
+ remainder = e.id[len(mod_prefix):]
319
877
  if "." not in remainder or (
320
878
  e.type == "function" and remainder.count(".") == 1
321
879
  ):
@@ -328,7 +886,7 @@ class KnowledgeGraphAnalyzer:
328
886
  )
329
887
 
330
888
  # contains 关系:类包含方法
331
- classes = [e for e in entities if e.type == "class"]
889
+ classes = [e for e in entities if e.type in ("class", "interface")]
332
890
  for cls in classes:
333
891
  cls_prefix = cls.id + "."
334
892
  for e in entities:
@@ -341,88 +899,116 @@ class KnowledgeGraphAnalyzer:
341
899
  )
342
900
  )
343
901
 
344
- # inherits 关系:类的 bases
902
+ # inherits 关系:类的 bases(已通过 _extract_class_bases 统一)
345
903
  for cls in classes:
346
904
  for base in cls.metadata.get("bases", []):
905
+ if not base or base == "Unknown":
906
+ continue
347
907
  target_id = self._resolve_entity_id(base, entity_map, cls.file_path)
348
908
  if target_id:
909
+ rel_type = "implements" if cls.type == "interface" else "inherits"
349
910
  relations.append(
350
911
  KGRelation(
351
912
  source_id=cls.id,
352
913
  target_id=target_id,
353
- type="inherits",
914
+ type=rel_type,
354
915
  )
355
916
  )
356
917
 
357
- # imports / depends_on 关系:从解析结果提取
358
- for fi in file_infos:
359
- # FileInfo 对象有 relative_path 属性
360
- file_path = fi.relative_path if hasattr(fi, "relative_path") else str(fi)
361
- module_id = self._file_to_module_id(file_path)
362
-
363
- parser = get_parser_for_file(file_path)
364
- if parser is None:
365
- continue
366
-
367
- try:
368
- code = Path(file_path).read_text(encoding="utf-8", errors="ignore")
369
- result = parser.parse_code(code, file_path)
370
- except Exception:
918
+ # imports 关系:从缓存的解析结果提取
919
+ for file_path, (module_id, result) in parse_cache.items():
920
+ language = self._detect_language(file_path)
921
+ # 查找对应的模块实体
922
+ mod_entity = entity_map.get(module_id)
923
+ if mod_entity is None:
371
924
  continue
372
925
 
373
926
  for imp in getattr(result, "imports", []):
374
- imp_module = getattr(imp, "module", None) or getattr(imp, "source", None) or ""
375
- if imp_module:
376
- # 尝试匹配项目内模块
377
- target_id = self._resolve_import_to_entity(imp_module, entity_map)
378
- if target_id:
379
- relations.append(
380
- KGRelation(
381
- source_id=module_id,
382
- target_id=target_id,
383
- type="imports",
384
- )
927
+ imp_module = self._extract_import_module(imp, language)
928
+ if not imp_module:
929
+ continue
930
+ # 尝试匹配项目内模块
931
+ target_id = self._resolve_import_to_entity(imp_module, entity_map)
932
+ if target_id:
933
+ relations.append(
934
+ KGRelation(
935
+ source_id=module_id,
936
+ target_id=target_id,
937
+ type="imports",
938
+ )
939
+ )
940
+
941
+ # calls 关系:从函数体中提取调用
942
+ for file_path, (module_id, result) in parse_cache.items():
943
+ language = self._detect_language(file_path)
944
+ calls = self._extract_calls_from_result(result, language)
945
+ for caller_suffix, callee_name in calls:
946
+ # 查找调用者实体
947
+ caller_id = self._find_entity_id_by_suffix(module_id, caller_suffix, entity_map)
948
+ if not caller_id:
949
+ continue
950
+ # 查找被调用者实体
951
+ callee_id = self._resolve_call_target(callee_name, caller_id, entity_map)
952
+ if callee_id and callee_id != caller_id:
953
+ relations.append(
954
+ KGRelation(
955
+ source_id=caller_id,
956
+ target_id=callee_id,
957
+ type="calls",
385
958
  )
959
+ )
386
960
 
387
961
  return relations
388
962
 
389
963
  def _detect_business_rules(
390
964
  self, entities: list[KGEntity], relations: list[KGRelation]
391
965
  ) -> list[KGBusinessRule]:
392
- """从实体和关系中检测业务规则"""
966
+ """从实体和关系中检测业务规则(语言感知)"""
393
967
  rules = []
394
968
  rule_id = 0
395
969
 
396
- # 命名约定检测
970
+ # 1. 语言感知命名约定检测
397
971
  for e in entities:
398
- if e.type == "class":
399
- if e.name and not re.match(r"^[A-Z]", e.name):
400
- rule_id += 1
401
- rules.append(
402
- KGBusinessRule(
972
+ language = self._detect_language(e.file_path)
973
+ if e.type in ("class", "interface"):
974
+ # Kotlin/Java: PascalCase; Python: PascalCase
975
+ if language in ("kotlin", "java"):
976
+ if e.name and not re.match(r"^[A-Z]", e.name):
977
+ rule_id += 1
978
+ rules.append(KGBusinessRule(
403
979
  id=f"BR{rule_id:03d}",
404
- description=f"类 '{e.name}' 未遵循大写开头命名约定",
405
- category="naming",
406
- entities=[e.id],
407
- source="static",
408
- )
409
- )
980
+ description=f"类 '{e.name}' 未遵循 PascalCase 命名约定",
981
+ category="naming", entities=[e.id], source="static",
982
+ ))
983
+ elif language == "python":
984
+ if e.name and not re.match(r"^[A-Z_]", e.name):
985
+ rule_id += 1
986
+ rules.append(KGBusinessRule(
987
+ id=f"BR{rule_id:03d}",
988
+ description=f"类 '{e.name}' 未遵循 PascalCase 命名约定",
989
+ category="naming", entities=[e.id], source="static",
990
+ ))
410
991
  elif e.type == "function":
411
- if e.name and not e.name.startswith("_") and not re.match(
412
- r"^[a-z_]", e.name
413
- ):
414
- rule_id += 1
415
- rules.append(
416
- KGBusinessRule(
992
+ if language in ("kotlin", "java"):
993
+ # camelCase
994
+ if e.name and not e.name.startswith("<") and not re.match(r"^[a-z]", e.name):
995
+ rule_id += 1
996
+ rules.append(KGBusinessRule(
417
997
  id=f"BR{rule_id:03d}",
418
- description=f"函数 '{e.name}' 未遵循蛇形命名约定",
419
- category="naming",
420
- entities=[e.id],
421
- source="static",
422
- )
423
- )
998
+ description=f"函数 '{e.name}' 未遵循 camelCase 命名约定",
999
+ category="naming", entities=[e.id], source="static",
1000
+ ))
1001
+ elif language == "python":
1002
+ # snake_case
1003
+ if e.name and not e.name.startswith("_") and not re.match(r"^[a-z_]", e.name):
1004
+ rule_id += 1
1005
+ rules.append(KGBusinessRule(
1006
+ id=f"BR{rule_id:03d}",
1007
+ description=f"函数 '{e.name}' 未遵循 snake_case 命名约定",
1008
+ category="naming", entities=[e.id], source="static",
1009
+ ))
424
1010
 
425
- # 架构约束:循环依赖检测
1011
+ # 2. 架构约束:循环依赖检测
426
1012
  module_ids = {e.id for e in entities if e.type == "module"}
427
1013
  import_rels = [r for r in relations if r.type == "imports"]
428
1014
  graph: dict[str, set[str]] = {m: set() for m in module_ids}
@@ -433,19 +1019,47 @@ class KnowledgeGraphAnalyzer:
433
1019
  cycles = self._find_cycles(graph)
434
1020
  for cycle in cycles:
435
1021
  rule_id += 1
436
- rules.append(
437
- KGBusinessRule(
438
- id=f"BR{rule_id:03d}",
439
- description=f"循环依赖: {' → '.join(cycle)}",
440
- category="constraint",
441
- entities=cycle,
442
- source="static",
443
- )
444
- )
1022
+ rules.append(KGBusinessRule(
1023
+ id=f"BR{rule_id:03d}",
1024
+ description=f"循环依赖: {' → '.join(cycle)}",
1025
+ category="constraint", entities=cycle, source="static",
1026
+ ))
1027
+
1028
+ # 3. 分层违规检测
1029
+ layer_rules = self._detect_layer_violations(entities, relations)
1030
+ for desc, eids in layer_rules:
1031
+ rule_id += 1
1032
+ rules.append(KGBusinessRule(
1033
+ id=f"BR{rule_id:03d}",
1034
+ description=desc, category="architecture",
1035
+ entities=eids, source="static",
1036
+ ))
1037
+
1038
+ # 4. 孤立实体检测
1039
+ orphans = self._detect_orphan_entities(entities, relations)
1040
+ if orphans:
1041
+ rule_id += 1
1042
+ rules.append(KGBusinessRule(
1043
+ id=f"BR{rule_id:03d}",
1044
+ description=f"发现 {len(orphans)} 个孤立实体(无任何关系): {', '.join(o.name for o in orphans[:10])}",
1045
+ category="architecture",
1046
+ entities=[o.id for o in orphans[:20]],
1047
+ source="static",
1048
+ ))
1049
+
1050
+ # 5. 依赖热点检测
1051
+ hotspots = self._detect_dependency_hotspots(entities, relations)
1052
+ for hs_name, hs_count in hotspots[:5]:
1053
+ rule_id += 1
1054
+ rules.append(KGBusinessRule(
1055
+ id=f"BR{rule_id:03d}",
1056
+ description=f"'{hs_name}' 是依赖热点(被 {hs_count} 个实体依赖),可能需要重构解耦",
1057
+ category="architecture", entities=[], source="static",
1058
+ ))
445
1059
 
446
- # 设计模式检测
1060
+ # 6. 设计模式检测
447
1061
  for cls in entities:
448
- if cls.type != "class":
1062
+ if cls.type not in ("class", "interface"):
449
1063
  continue
450
1064
  bases = cls.metadata.get("bases", [])
451
1065
  methods = cls.metadata.get("methods", [])
@@ -453,40 +1067,85 @@ class KnowledgeGraphAnalyzer:
453
1067
  # 单例模式
454
1068
  if any("_instance" in m for m in methods) and "__new__" in methods:
455
1069
  rule_id += 1
456
- rules.append(
457
- KGBusinessRule(
458
- id=f"BR{rule_id:03d}",
459
- description=f"类 '{cls.name}' 可能使用单例模式",
460
- category="pattern",
461
- entities=[cls.id],
462
- source="static",
463
- )
464
- )
1070
+ rules.append(KGBusinessRule(
1071
+ id=f"BR{rule_id:03d}",
1072
+ description=f"类 '{cls.name}' 可能使用单例模式",
1073
+ category="pattern", entities=[cls.id], source="static",
1074
+ ))
465
1075
 
466
1076
  # 工厂模式
467
- if any(
468
- "create" in m or "build" in m or "make" in m for m in methods
469
- ) and not bases:
1077
+ if any("create" in m or "build" in m or "make" in m for m in methods) and not bases:
470
1078
  rule_id += 1
471
- rules.append(
472
- KGBusinessRule(
473
- id=f"BR{rule_id:03d}",
474
- description=f"类 '{cls.name}' 可能使用工厂模式",
475
- category="pattern",
476
- entities=[cls.id],
477
- source="static",
478
- )
479
- )
1079
+ rules.append(KGBusinessRule(
1080
+ id=f"BR{rule_id:03d}",
1081
+ description=f"类 '{cls.name}' 可能使用工厂模式",
1082
+ category="pattern", entities=[cls.id], source="static",
1083
+ ))
480
1084
 
481
1085
  return rules
482
1086
 
1087
+ @staticmethod
1088
+ def _detect_layer_violations(entities: list[KGEntity], relations: list[KGRelation]) -> list[tuple[str, list[str]]]:
1089
+ """检测分层架构违规(controller→service→domain→infrastructure)"""
1090
+ violations = []
1091
+ layer_keywords = {
1092
+ "controller": ["controller", "api", "endpoint", "handler", "resource", "rest"],
1093
+ "service": ["service", "application", "usecase", "use_case", "command", "query"],
1094
+ "domain": ["domain", "model", "entity", "value", "aggregate", "event"],
1095
+ "infrastructure": ["infrastructure", "repo", "repository", "persistence", "client", "config", "adapter"],
1096
+ }
1097
+
1098
+ def _infer_layer(entity: KGEntity) -> str | None:
1099
+ path_lower = entity.file_path.lower() + "." + entity.name.lower()
1100
+ for layer, keywords in layer_keywords.items():
1101
+ for kw in keywords:
1102
+ if kw in path_lower:
1103
+ return layer
1104
+ return None
1105
+
1106
+ layer_order = {"controller": 0, "service": 1, "domain": 2, "infrastructure": 3}
1107
+
1108
+ for r in relations:
1109
+ if r.type not in ("imports", "depends_on", "calls"):
1110
+ continue
1111
+ src = next((e for e in entities if e.id == r.source_id), None)
1112
+ tgt = next((e for e in entities if e.id == r.target_id), None)
1113
+ if not src or not tgt:
1114
+ continue
1115
+ src_layer = _infer_layer(src)
1116
+ tgt_layer = _infer_layer(tgt)
1117
+ if src_layer and tgt_layer and layer_order.get(src_layer, 99) < layer_order.get(tgt_layer, 99):
1118
+ violations.append((
1119
+ f"分层违规: {src_layer} 层 '{src.name}' 直接依赖 {tgt_layer} 层 '{tgt.name}'",
1120
+ [src.id, tgt.id],
1121
+ ))
1122
+
1123
+ return violations
1124
+
1125
+ @staticmethod
1126
+ def _detect_orphan_entities(entities: list[KGEntity], relations: list[KGRelation]) -> list[KGEntity]:
1127
+ """检测没有任何关系的实体(排除模块实体)"""
1128
+ related_ids: set[str] = set()
1129
+ for r in relations:
1130
+ related_ids.add(r.source_id)
1131
+ related_ids.add(r.target_id)
1132
+ return [e for e in entities if e.type not in ("module",) and e.id not in related_ids]
1133
+
1134
+ @staticmethod
1135
+ def _detect_dependency_hotspots(entities: list[KGEntity], relations: list[KGRelation]) -> list[tuple[str, int]]:
1136
+ """检测被依赖最多的实体(热点),返回 [(entity_name, incoming_count)]"""
1137
+ incoming: dict[str, int] = {}
1138
+ for r in relations:
1139
+ if r.type in ("imports", "depends_on", "calls", "inherits", "implements"):
1140
+ incoming[r.target_id] = incoming.get(r.target_id, 0) + 1
1141
+ entity_name_map = {e.id: e.name for e in entities}
1142
+ hotspots = [(entity_name_map.get(eid, eid), count) for eid, count in incoming.items() if count >= 3]
1143
+ hotspots.sort(key=lambda x: -x[1])
1144
+ return hotspots
1145
+
483
1146
  def _enhance_with_llm(self, kg: KnowledgeGraph) -> KnowledgeGraph:
484
1147
  """使用 LLM 增强知识图谱(推断隐含业务规则和语义关系)"""
485
1148
  try:
486
- from core.llm_client import LLMClient
487
-
488
- llm = LLMClient(self.analyzer.config.llm)
489
-
490
1149
  # 构建摘要供 LLM 分析
491
1150
  summary = self._build_kg_summary(kg)
492
1151
  prompt = (
@@ -497,7 +1156,7 @@ class KnowledgeGraphAnalyzer:
497
1156
  '2. "suggested_relations": [{source_id, target_id, type, description}]\n'
498
1157
  )
499
1158
 
500
- response = llm.analyze(prompt)
1159
+ response = self.analyzer.llm.simple_chat(prompt)
501
1160
  if response:
502
1161
  from core.json_utils import JSONUtils
503
1162
 
@@ -531,6 +1190,105 @@ class KnowledgeGraphAnalyzer:
531
1190
 
532
1191
  # ── 辅助方法 ──────────────────────────────────────────
533
1192
 
1193
+ @staticmethod
1194
+ def _extract_calls_from_result(result, language: str) -> list[tuple[str, str]]:
1195
+ """从解析结果中提取函数调用关系,返回 [(caller_suffix, callee_name), ...]"""
1196
+ calls = []
1197
+
1198
+ # 从类方法中提取调用
1199
+ for cls in getattr(result, "classes", []):
1200
+ cls_name = getattr(cls, "name", "")
1201
+ if not cls_name or cls_name == "Unknown":
1202
+ continue
1203
+ for method in getattr(cls, "functions", []) or getattr(cls, "methods", []):
1204
+ method_name = getattr(method, "name", "")
1205
+ if not method_name:
1206
+ continue
1207
+ caller_suffix = f"{cls_name}.{method_name}"
1208
+ # 从方法体中提取调用
1209
+ callees = KnowledgeGraphAnalyzer._extract_callees_from_method(method, language)
1210
+ for callee in callees:
1211
+ calls.append((caller_suffix, callee))
1212
+
1213
+ # 从模块级函数中提取调用
1214
+ for func in getattr(result, "functions", []):
1215
+ func_name = getattr(func, "name", "")
1216
+ if not func_name:
1217
+ continue
1218
+ callees = KnowledgeGraphAnalyzer._extract_callees_from_method(func, language)
1219
+ for callee in callees:
1220
+ calls.append((func_name, callee))
1221
+
1222
+ return calls
1223
+
1224
+ @staticmethod
1225
+ def _extract_callees_from_method(method_obj, language: str) -> list[str]:
1226
+ """从方法/函数对象中提取被调用的函数名"""
1227
+ callees = []
1228
+ # 尝试从 body/source 字段提取
1229
+ body = getattr(method_obj, "body", None) or getattr(method_obj, "source", None)
1230
+ if body and isinstance(body, str):
1231
+ callees.extend(KnowledgeGraphAnalyzer._parse_calls_from_source(body, language))
1232
+ return callees
1233
+
1234
+ @staticmethod
1235
+ def _parse_calls_from_source(source: str, language: str) -> list[str]:
1236
+ """从源代码文本中提取函数调用名"""
1237
+ calls = set()
1238
+ if language == "python":
1239
+ # 匹配 func_name(...) 和 obj.method(...) 模式
1240
+ for m in re.finditer(r'(?:^|[\s.=])((?:[a-zA-Z_]\w*\.)*[a-zA-Z_]\w*)\s*\(', source):
1241
+ name = m.group(1)
1242
+ # 取最后一段作为函数名
1243
+ parts = name.split(".")
1244
+ if parts[-1] not in ("if", "for", "while", "with", "try", "class", "def", "return", "print", "len", "str", "int", "list", "dict", "set", "tuple", "range", "isinstance", "hasattr", "getattr", "setattr", "super", "property", "staticmethod", "classmethod"):
1245
+ calls.add(parts[-1])
1246
+ elif language == "kotlin":
1247
+ # 匹配 funName(...) 和 obj.method(...) 模式
1248
+ for m in re.finditer(r'(?:^|[\s.=\(])((?:[a-zA-Z_]\w*\.)*[a-zA-Z_]\w*)\s*\(', source):
1249
+ name = m.group(1)
1250
+ parts = name.split(".")
1251
+ if parts[-1] not in ("if", "for", "while", "when", "try", "class", "fun", "val", "var", "return", "println", "print", "let", "apply", "run", "also", "with", "use", "forEach", "map", "filter", "toList", "first", "last", "size", "is", "as", "in", "to"):
1252
+ calls.add(parts[-1])
1253
+ else:
1254
+ # 通用匹配
1255
+ for m in re.finditer(r'([a-zA-Z_]\w*)\s*\(', source):
1256
+ name = m.group(1)
1257
+ if name not in ("if", "for", "while", "try", "class", "function", "return", "new", "throw", "switch", "catch"):
1258
+ calls.add(name)
1259
+ return list(calls)
1260
+
1261
+ @staticmethod
1262
+ def _find_entity_id_by_suffix(module_id: str, suffix: str, entity_map: dict) -> str | None:
1263
+ """通过模块 ID + 后缀查找实体 ID"""
1264
+ candidate = f"{module_id}.{suffix}"
1265
+ if candidate in entity_map:
1266
+ return candidate
1267
+ # 模糊匹配
1268
+ for eid in entity_map:
1269
+ if eid.endswith(f".{suffix}"):
1270
+ return eid
1271
+ return None
1272
+
1273
+ @staticmethod
1274
+ def _resolve_call_target(callee_name: str, caller_id: str, entity_map: dict) -> str | None:
1275
+ """解析调用目标实体 ID"""
1276
+ # 直接匹配
1277
+ if callee_name in entity_map:
1278
+ return callee_name
1279
+ # 在调用者同模块中查找
1280
+ parts = caller_id.rsplit(".", 1)
1281
+ if len(parts) > 1:
1282
+ module_prefix = parts[0]
1283
+ candidate = f"{module_prefix}.{callee_name}"
1284
+ if candidate in entity_map:
1285
+ return candidate
1286
+ # 全局模糊匹配
1287
+ for eid in entity_map:
1288
+ if eid.endswith(f".{callee_name}"):
1289
+ return eid
1290
+ return None
1291
+
534
1292
  @staticmethod
535
1293
  def _file_to_module_id(file_path: str) -> str:
536
1294
  """将文件路径转换为模块 ID"""