ci / ubuntu-latest / clang (push) Failing after 53s
ci / ubuntu-latest / gcc (push) Failing after 36s
ci / coverage / gcc (push) Failing after 35s
ci / macos-latest / apple-clang (push) Canceled after 0s
ci / windows-latest / mingw (push) Canceled after 0s
ci / windows-latest / msvc (push) Canceled after 0s
428 lines
18 KiB
Python
428 lines
18 KiB
Python
#!/usr/bin/env python3
|
||
"""VDCS API 手册生成器(P3-S4-04;22-用户文档与帮助系统 §3,主流程 §13.1)。
|
||
|
||
流程:Doxygen(XML)解析 include/vdcs 公共头 → 按模块生成 docs/api/:
|
||
README.md 模块总览 + 目录索引 + 统计
|
||
{module}.md 模块手册(职责/头文件/类参考/函数字典/枚举)
|
||
examples.md / call-graph.md 为人工维护的场景文档,本工具不覆盖。
|
||
|
||
用法(仓库根):
|
||
python tools/api/gen_api_docs.py [--source <repo>] [--output docs/api]
|
||
[--doxygen <exe>] [--keep-xml]
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import datetime
|
||
import html
|
||
import pathlib
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import xml.etree.ElementTree as ET
|
||
|
||
# ---- 模块映射:头文件(include/vdcs/ 相对路径)→ (模块, 一句话职责) ------------
|
||
MODULE_OF_HEADER = {
|
||
"model/model.h": "model",
|
||
"model/entity.h": "model",
|
||
"model/constraint.h": "model",
|
||
"model/constraint3d.h": "model",
|
||
"model/geometry_adapter.h": "model",
|
||
"model/external_constraint.h": "model",
|
||
"geom/vec2.h": "geom",
|
||
"geom/vec3.h": "geom",
|
||
"geom/quaternion.h": "geom",
|
||
"geom/line3.h": "geom",
|
||
"geom/plane3.h": "geom",
|
||
"core/newton_solver.h": "core",
|
||
"core/sparse_lm_solver.h": "core",
|
||
"core/decomposer.h": "core",
|
||
"core/decomposed_solver.h": "core",
|
||
"core/incremental.h": "core",
|
||
"core/branch_selector.h": "core",
|
||
"core/expression.h": "core",
|
||
"core/solver_strategy.h": "core",
|
||
"core/diagnostic.h": "core",
|
||
"core/dof_analyzer.h": "core",
|
||
"core/constraint_graph.h": "core",
|
||
"core/solve_context.h": "core",
|
||
"core/dogleg_solver.h": "core",
|
||
"core/multi_start_solver.h": "core",
|
||
"core/drag_controller.h": "core",
|
||
"io/serializer.h": "io",
|
||
"infra/uid.h": "infra",
|
||
"infra/error.h": "infra",
|
||
"infra/log.h": "infra",
|
||
"c_api/vdcs_c_api.h": "c_api",
|
||
}
|
||
|
||
# 模块元数据(职责 + 依赖,生成到手册头;依赖关系同 call-graph.md)
|
||
MODULE_META = {
|
||
"model": (
|
||
"建模门面:实体/约束工厂(2D+3D 全集)、外部几何适配(宿主样条/"
|
||
"自由曲线投影)、变量与表达式、求解入口、外部拓扑命名适配(P-08)"
|
||
"——宿主 90% 场景只接触本模块",
|
||
"core(求解委托)、io(加载/保存)、infra"),
|
||
"geom": (
|
||
"2D/3D 基础几何与 SO(3) 数学:向量、四元数(ExpMap/LogMap)、"
|
||
"直线/平面解析几何",
|
||
"infra"),
|
||
"core": (
|
||
"求解内核:数值引擎(Newton/SparseLM/DogLeg 信赖域/分解/增量)+ "
|
||
"多起点重启、拖拽会话控制、策略框架、DOF 分析、图分解、诊断、"
|
||
"表达式求值、多解分支",
|
||
"geom、infra"),
|
||
"io": (
|
||
"模型序列化:二进制(版本化紧凑格式)与 JSON 双路径往返",
|
||
"model、infra"),
|
||
"infra": (
|
||
"横切基础:错误码与 Result<T>、稳定 UID、日志",
|
||
"—"),
|
||
"c_api": (
|
||
"纯 C ABI 边界(09-API §2 唯一稳定边界,签名冻结 + CI 检查)",
|
||
"model、infra"),
|
||
}
|
||
MODULE_ORDER = ["model", "geom", "core", "io", "infra", "c_api"]
|
||
|
||
DOXYFILE_TEMPLATE = """\
|
||
GENERATE_XML = YES
|
||
XML_OUTPUT = {xml_dir}
|
||
GENERATE_HTML = NO
|
||
GENERATE_LATEX = NO
|
||
INPUT = {input_dir}
|
||
RECURSIVE = YES
|
||
EXTRACT_ALL = YES
|
||
EXTRACT_PRIVATE = NO
|
||
EXTRACT_STATIC = YES
|
||
CASE_SENSE_NAMES = NO
|
||
QUIET = YES
|
||
WARNINGS = NO
|
||
WARN_IF_UNDOCUMENTED = NO
|
||
SORT_MEMBER_DOCS = NO
|
||
SORT_BRIEF_DOCS = NO
|
||
ENABLE_PREPROCESSING = YES
|
||
"""
|
||
|
||
|
||
def fail(msg: str) -> None:
|
||
print(f"gen_api_docs: ERROR: {msg}", file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
|
||
# ---- Doxygen -----------------------------------------------------------------
|
||
def run_doxygen(source: pathlib.Path, doxygen: str, xml_dir: pathlib.Path) -> None:
|
||
doxyfile = xml_dir / "Doxyfile"
|
||
doxyfile.write_text(
|
||
DOXYFILE_TEMPLATE.format(xml_dir=str(xml_dir).replace("\\", "/"),
|
||
input_dir=str(source / "include" / "vdcs").replace("\\", "/")),
|
||
encoding="utf-8")
|
||
proc = subprocess.run([doxygen, str(doxyfile)], capture_output=True, text=True)
|
||
if proc.returncode != 0:
|
||
fail(f"doxygen 失败 (exit={proc.returncode}): {proc.stderr[:2000]}")
|
||
|
||
|
||
# ---- XML 解析 ----------------------------------------------------------------
|
||
def para_text(node) -> str:
|
||
"""取 Doxygen 描述节点的纯文本(para 拼接,去 HTML 标签语义只留文字)。"""
|
||
if node is None:
|
||
return ""
|
||
parts = []
|
||
for para in node.findall("./para"):
|
||
parts.append("".join(para.itertext()).strip())
|
||
return " ".join(p for p in parts if p)
|
||
|
||
|
||
def header_of(location_file: str) -> str:
|
||
"""location 形如 <repo>/include/vdcs/model/model.h → model/model.h。"""
|
||
norm = location_file.replace("\\", "/")
|
||
marker = "include/vdcs/"
|
||
idx = norm.find(marker)
|
||
return norm[idx + len(marker):] if idx >= 0 else ""
|
||
|
||
|
||
def compound_header_of(kind: str, root) -> str:
|
||
"""compounddef 自身的 location → 头文件路径(类/文件归属兜底)。"""
|
||
loc = root.find("./location")
|
||
if loc is None:
|
||
return ""
|
||
return header_of(loc.get("file", ""))
|
||
|
||
|
||
def parse_compounds(xml_dir: pathlib.Path):
|
||
"""返回 {module: {"classes": [...], "functions": [...], "enums_memberdef": [],
|
||
"attribs_memberdef": [...]}}。
|
||
|
||
classes: {name, brief, header, methods[], enums[], attrs[]}
|
||
functions: 模块级自由函数 {name, sig, brief, header}
|
||
compound 处理顺序 class/struct/namespace → file(file 视图与 namespace
|
||
视图重复的签名去重;extern "C" 全局函数仅存在于 file 视图,如 C ABI)
|
||
"""
|
||
buckets: dict = {m: {"classes": [], "functions": [], "enums_memberdef": [],
|
||
"attribs_memberdef": []} for m in MODULE_ORDER}
|
||
|
||
index = ET.parse(xml_dir / "index.xml").getroot()
|
||
compounds = [(c.get("kind", ""), c.get("refid"))
|
||
for c in index.findall("./compound")
|
||
if c.get("kind", "") in ("class", "struct", "namespace", "file")]
|
||
# class/namespace 视图优先;file 视图兜底补 extern "C" 全局符号
|
||
compounds.sort(key=lambda kc: 0 if kc[0] != "file" else 1)
|
||
seen_sigs: set[str] = set()
|
||
|
||
for kind, refid in compounds:
|
||
root = ET.parse(xml_dir / f"{refid}.xml").getroot().find("./compounddef")
|
||
if root is None:
|
||
continue
|
||
owner_name = ""
|
||
if kind in ("class", "struct"):
|
||
owner_name = html.unescape(root.findtext("./compoundname") or "")
|
||
compound_loc = root.find("./location")
|
||
compound_header = (header_of(compound_loc.get("file", ""))
|
||
if compound_loc is not None else "")
|
||
if compound_header in MODULE_OF_HEADER:
|
||
module = MODULE_OF_HEADER[compound_header]
|
||
buckets[module]["classes"].append({
|
||
"name": owner_name, "brief": html.unescape(
|
||
para_text(root.find("./briefdescription"))),
|
||
"header": compound_header,
|
||
"methods": [], "enums": [], "attrs": []})
|
||
|
||
for section in root.findall("./sectiondef"):
|
||
skind = section.get("kind", "")
|
||
# 类成员: public-func/public-attrib/...;自由函数: func;
|
||
# 文件视图枚举/typedef(C ABI 匿名枚举、回调签名等)
|
||
if not (skind.startswith("public") or skind == "func"
|
||
or (kind == "file" and skind in ("enum", "typedef"))):
|
||
continue
|
||
for md in section.findall("./memberdef"):
|
||
if md.get("prot") != "public":
|
||
continue
|
||
mkind = md.get("kind", "")
|
||
loc = md.find("./location")
|
||
# location 优先(声明/定义处);无 location 或指向 .cpp 定义时
|
||
# 回退 compound 所在头文件(类成员尤其如此)
|
||
hdr = (header_of(loc.get("file", "")) if loc is not None else "")
|
||
if hdr not in MODULE_OF_HEADER:
|
||
hdr = compound_header_of(kind, root)
|
||
if hdr not in MODULE_OF_HEADER:
|
||
continue # Eigen/STL 展开、无名内部定义
|
||
module = MODULE_OF_HEADER[hdr]
|
||
name = (md.findtext("./name") or "").strip()
|
||
if not name or name.startswith("~") or name.startswith("operator"):
|
||
continue
|
||
brief = html.unescape(para_text(md.find("./briefdescription")))
|
||
detail = html.unescape(para_text(md.find("./detaileddescription")))
|
||
doc = (f"{brief} {detail}").strip()
|
||
|
||
if mkind == "function":
|
||
sig = md.findtext("./definition") or name
|
||
args = md.findtext("./argsstring") or ""
|
||
sig = html.unescape(f"{sig}{args}")
|
||
if kind == "file": # 兜底视图:先按签名去重
|
||
if sig in seen_sigs:
|
||
continue
|
||
seen_sigs.add(sig)
|
||
buckets[module]["functions"].append(
|
||
{"name": name, "sig": sig, "brief": doc,
|
||
"header": hdr, "owner": owner_name or None})
|
||
elif mkind == "typedef":
|
||
sig = html.unescape(
|
||
f"{md.findtext('./definition') or name}"
|
||
f"{md.findtext('./argsstring') or ''}")
|
||
if kind == "file":
|
||
if sig in seen_sigs:
|
||
continue
|
||
seen_sigs.add(sig)
|
||
buckets[module]["functions"].append(
|
||
{"name": name, "sig": sig, "brief": doc,
|
||
"header": hdr, "owner": owner_name or None})
|
||
elif mkind == "enum":
|
||
values = []
|
||
for ev in md.findall("./enumvalue"):
|
||
vname = (ev.findtext("./name") or "").strip()
|
||
vdesc = (f"{para_text(ev.find('./briefdescription'))} "
|
||
f"{para_text(ev.find('./detaileddescription'))}"
|
||
).strip()
|
||
values.append((vname, vdesc))
|
||
if name.startswith("@"): # 匿名枚举(C ABI 常见)
|
||
name = "<匿名枚举>"
|
||
sig = html.unescape(md.findtext("./definition") or name)
|
||
buckets[module]["enums_memberdef"].append(
|
||
{"name": name, "sig": sig, "brief": doc,
|
||
"values": values, "header": hdr,
|
||
"owner": owner_name or None})
|
||
elif mkind == "variable": # 公共字段/常量
|
||
sig = html.unescape(
|
||
f"{md.findtext('./type') or ''} {name}").strip()
|
||
if kind == "file":
|
||
if sig in seen_sigs:
|
||
continue
|
||
seen_sigs.add(sig)
|
||
buckets[module]["attribs_memberdef"].append(
|
||
{"name": name, "sig": sig, "brief": doc,
|
||
"header": hdr, "owner": owner_name or None})
|
||
return buckets
|
||
|
||
|
||
def attach_members(buckets) -> None:
|
||
"""把 memberdef(方法/枚举/字段)按 owner 挂回所属类;无 owner 的进模块级。"""
|
||
for module, data in buckets.items():
|
||
by_name = {c["name"]: c for c in data["classes"]}
|
||
free_funcs = []
|
||
for f in data["functions"]:
|
||
owner = f.pop("owner", None)
|
||
if owner and owner in by_name:
|
||
by_name[owner]["methods"].append(
|
||
{"name": f["name"], "sig": f["sig"], "brief": f["brief"]})
|
||
else:
|
||
free_funcs.append(f)
|
||
data["functions"] = free_funcs
|
||
for e in data["enums_memberdef"]:
|
||
owner = e.pop("owner", None)
|
||
if owner and owner in by_name:
|
||
by_name[owner]["enums"].append(e)
|
||
else:
|
||
e.pop("header", None)
|
||
data["functions"].append(e)
|
||
for a in data["attribs_memberdef"]:
|
||
owner = a.pop("owner", None)
|
||
if owner and owner in by_name:
|
||
by_name[owner]["attrs"].append(a)
|
||
else:
|
||
a.pop("header", None)
|
||
data["functions"].append(a)
|
||
|
||
|
||
# ---- 渲染 --------------------------------------------------------------------
|
||
def render_module(module: str, data: dict, date: str) -> str:
|
||
desc, deps = MODULE_META[module]
|
||
headers = sorted({c["header"] for c in data["classes"]} |
|
||
{f["header"] for f in data["functions"]
|
||
if f.get("header")})
|
||
lines = [
|
||
f"# {module} 模块", "",
|
||
f"> AI 自动生成,基于源代码扫描(Doxygen)。最后更新: {date} ",
|
||
"> 再生成: `python tools/api/gen_api_docs.py`(examples.md / call-graph.md 人工维护,不覆盖)",
|
||
"",
|
||
"## 职责", "", desc, "",
|
||
"## 依赖", "", deps, "",
|
||
"## 头文件", "",
|
||
]
|
||
lines += [f"- `include/vdcs/{h}`" for h in headers]
|
||
|
||
for cls in sorted(data["classes"], key=lambda c: c["name"]):
|
||
lines += ["", f"## {cls['name']}", ""]
|
||
if cls["brief"]:
|
||
lines += [cls["brief"], ""]
|
||
lines += [f"头文件: `include/vdcs/{cls['header']}`", ""]
|
||
methods = cls.get("methods", [])
|
||
if methods:
|
||
lines += ["### 方法", "",
|
||
"| 方法 | 签名 | 说明 |", "|------|------|------|"]
|
||
for m in sorted(methods, key=lambda m: m["name"]):
|
||
sig = m["sig"].replace("|", "\\|")
|
||
desc_m = m["brief"].replace("|", "\\|") or "{待补充}"
|
||
lines.append(f"| `{m['name']}` | `{sig}` | {desc_m} |")
|
||
enums = cls.get("enums", [])
|
||
if enums:
|
||
lines += ["", "### 枚举", ""]
|
||
for e in enums:
|
||
lines += [f"**`{e['name']}`** {e['brief']}", ""]
|
||
lines += ["| 值 | 说明 |", "|----|------|"]
|
||
lines += [f"| `{v}` | {d or '—'} |" for v, d in e["values"]]
|
||
attrs = cls.get("attrs", [])
|
||
if attrs:
|
||
lines += ["", "### 字段", "",
|
||
"| 字段 | 类型 | 说明 |", "|------|------|------|"]
|
||
for a in sorted(attrs, key=lambda a: a["name"]):
|
||
sig = a["sig"].replace("|", "\\|")
|
||
desc_a = a["brief"].replace("|", "\\|") or "{待补充}"
|
||
lines.append(f"| `{a['name']}` | `{sig}` | {desc_a} |")
|
||
|
||
if data["functions"]:
|
||
lines += ["", "## 模块级函数 / 常量 / 枚举", "",
|
||
"| 名称 | 签名 / 值 | 说明 |", "|------|-----------|------|"]
|
||
for f in sorted(data["functions"], key=lambda f: f["name"]):
|
||
sig = f["sig"].replace("|", "\\|")
|
||
desc_f = f["brief"].replace("|", "\\|") or "{待补充}"
|
||
lines.append(f"| `{f['name']}` | `{sig}` | {desc_f} |")
|
||
for v, d in f.get("values", []):
|
||
lines.append(f"| `{v}` | — | {d or '—'} |")
|
||
return "\n".join(lines) + "\n"
|
||
|
||
|
||
def render_readme(stats: dict, date: str) -> str:
|
||
lines = [
|
||
"# VDCS 使用助手(API 手册)", "",
|
||
f"> AI 自动生成,基于源代码扫描(Doxygen)。最后更新: {date} ",
|
||
"> 再生成: `python tools/api/gen_api_docs.py`(或 `cmake --build <build> --target vdcs_apidoc`)",
|
||
"",
|
||
"统一入口 `#include <vdcs/vdcs.h>`(C ABI 独立边界: `#include <vdcs/c_api/vdcs_c_api.h>`)。"
|
||
"错误处理统一 `Result<T>`(16-编码规范 §3);性能门禁/ABI 冻结/发布物说明见 CHANGELOG.md。",
|
||
"",
|
||
"## 快速导航", "",
|
||
"| 模块 | 说明 | 手册 | 类 | 函数/枚举 |",
|
||
"|------|------|------|----|----------|",
|
||
]
|
||
for m in MODULE_ORDER:
|
||
desc, _ = MODULE_META[m]
|
||
lines.append(
|
||
f"| {m} | {desc.split(':')[0]} | [{m}.md]({m}.md) "
|
||
f"| {stats[m]['classes']} | {stats[m]['functions']} |")
|
||
lines += [
|
||
"", "## 场景文档(人工维护)", "",
|
||
"- [examples.md](examples.md) — 常见用法速查(集成/建模/求解/诊断/增量/表达式/"
|
||
"序列化/多解/回调/拖拽/策略/C ABI,示例均取自已验证代码)",
|
||
"- [call-graph.md](call-graph.md) — 模块调用关系图",
|
||
"",
|
||
"## 文档层级(22-用户文档 §2)", "",
|
||
"L1 快速上手 README+examples/ → L2 本 API 参考 → L3 概念指南 docs/design/ "
|
||
"→ L4 示例集 examples/ → L5 高级主题 06-插件SDK。",
|
||
]
|
||
return "\n".join(lines) + "\n"
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser(description="VDCS API 手册生成器")
|
||
ap.add_argument("--source", default=str(pathlib.Path(__file__).resolve().parents[2]))
|
||
ap.add_argument("--output", default=None,
|
||
help="默认 <source>/docs/api")
|
||
ap.add_argument("--doxygen", default="doxygen")
|
||
ap.add_argument("--keep-xml", action="store_true")
|
||
args = ap.parse_args()
|
||
|
||
source = pathlib.Path(args.source).resolve()
|
||
out_dir = pathlib.Path(args.output).resolve() if args.output \
|
||
else source / "docs" / "api"
|
||
if shutil.which(args.doxygen) is None:
|
||
fail(f"未找到 doxygen(PATH)——安装后重试")
|
||
|
||
date = datetime.date.today().isoformat()
|
||
with tempfile.TemporaryDirectory(prefix="vdcs_apidoc_") as tmp:
|
||
xml_dir = pathlib.Path(tmp)
|
||
run_doxygen(source, args.doxygen, xml_dir)
|
||
buckets = parse_compounds(xml_dir)
|
||
attach_members(buckets)
|
||
|
||
stats = {}
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
for m in MODULE_ORDER:
|
||
md = render_module(m, buckets[m], date)
|
||
(out_dir / f"{m}.md").write_text(md, encoding="utf-8")
|
||
n_cls = len(buckets[m]["classes"])
|
||
n_fn = len(buckets[m]["functions"]) + \
|
||
sum(len(c.get("methods", [])) for c in buckets[m]["classes"])
|
||
stats[m] = {"classes": n_cls, "functions": n_fn}
|
||
print(f"gen_api_docs: {m}.md —— {n_cls} 类 / {n_fn} 方法与函数")
|
||
(out_dir / "README.md").write_text(render_readme(stats, date),
|
||
encoding="utf-8")
|
||
print(f"gen_api_docs: README.md + {len(MODULE_ORDER)} 模块手册 -> {out_dir}")
|
||
if args.keep_xml:
|
||
keep = pathlib.Path("apidoc-xml")
|
||
shutil.copytree(xml_dir, keep, dirs_exist_ok=True)
|
||
print(f"gen_api_docs: XML 保留于 {keep.resolve()}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|