[libc-commits] [libc] [libc][docs] Check entrypoints and filter stubs in docgen (PR #238908)
via libc-commits
libc-commits at lists.llvm.org
Wed Nov 4 11:04:44 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-libc
Author: Jeff Bailey (kaladron)
<details>
<summary>Changes</summary>
Header status pages generated by docgen previously marked a function as implemented whenever a matching .cpp file existed under libc/src/<header>/. That check produced false positives for placeholder files containing only a TODO comment and an ENOSYS return (such as dlfcn.h, glob.h, and nl_types.h), and false negatives for functions implemented in shared subdirectories (such as htonl in libc/src/network/ for netinet/in.h or select in libc/src/sys/select/ for sys/time.h). Macro detection similarly missed definitions coming from shared macro_header entries or enums in libc/include/<header>.yaml, legacy .h.def templates (assert.h, errno.h), and compiler-provided freestanding headers (float.h). Generated header pages also had broken Furo View and Edit links because their .rst files exist only in the build directory.
Update Header.implements_fn to check the union of exported symbols across config/**/entrypoints.txt while excluding source files whose only implementation is a TODO stub, and expand Header.implements_macro to cover macro_header, enum, .h.def, and freestanding definitions. Add an html-page-context hook in conf.py so View and Edit links on generated header pages point to their corresponding libc/utils/docgen/<header>.yaml specification.
Assisted-by: Automated tooling, human reviewed.
---
Full diff: https://github.com/llvm/llvm-project/pull/238908.diff
5 Files Affected:
- (modified) libc/docs/conf.py (+25-1)
- (modified) libc/docs/dev/building_docs.md (+3-3)
- (modified) libc/utils/docgen/docgen.py (+9-15)
- (added) libc/utils/docgen/docgen_test.py (+58)
- (modified) libc/utils/docgen/header.py (+166-46)
``````````diff
diff --git a/libc/docs/conf.py b/libc/docs/conf.py
index 3aa9738922b954..d93c1aeded9526 100644
--- a/libc/docs/conf.py
+++ b/libc/docs/conf.py
@@ -1,4 +1,10 @@
-# -*- coding: utf-8 -*-
+# ===----------------------------------------------------------------------===##
+#
+# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+#
+# ===----------------------------------------------------------------------===##
#
# libc documentation build configuration file.
#
@@ -12,6 +18,7 @@
import sys, os
from datetime import date
+from pathlib import Path
from llvm_sphinx import * # see llvm-project/utils/docs/README.md
@@ -248,3 +255,20 @@
todo_include_todos = True
redirects = {"math/index": "../headers/math/index.html"}
+
+
+def _configure_generated_header_links(app, pagename, templatename, context, doctree):
+ if not pagename.startswith("headers/"):
+ return
+ stem = pagename[len("headers/") :]
+ yaml_rel = f"libc/utils/docgen/{stem}.yaml"
+ for p in Path(__file__).resolve().parents:
+ if (p / yaml_rel).exists():
+ repo = "https://github.com/llvm/llvm-project"
+ context["theme_source_view_link"] = f"{repo}/blob/main/{yaml_rel}?plain=1"
+ context["theme_source_edit_link"] = f"{repo}/edit/main/{yaml_rel}"
+ break
+
+
+def setup(app):
+ app.connect("html-page-context", _configure_generated_header_links)
diff --git a/libc/docs/dev/building_docs.md b/libc/docs/dev/building_docs.md
index cf262827c9ab49..a1b3e99f4b502e 100644
--- a/libc/docs/dev/building_docs.md
+++ b/libc/docs/dev/building_docs.md
@@ -62,9 +62,9 @@ The per-header implementation status pages under `docs/headers/` are
**not** hand-written RST. They are generated at build time by
`libc/utils/docgen/docgen.py`, which:
-1. Reads YAML function definitions from `libc/src/<header>/*.yaml`.
-2. Scans `libc/src/<header>/` for `.cpp` implementation files.
-3. Checks `libc/include/llvm-libc-macros/` for macro `#define` entries.
+1. Reads YAML function and macro definitions from `libc/utils/docgen/<header>.yaml`.
+2. Checks implementation status against platform `entrypoints.txt` files (excluding `TODO` stubs).
+3. Checks `libc/include/llvm-libc-macros/` and `libc/include/<header>.yaml` for macro definitions.
4. Emits an RST `list-table` showing each symbol's implementation status,
C standard section, and POSIX link.
diff --git a/libc/utils/docgen/docgen.py b/libc/utils/docgen/docgen.py
index 9ee87a97b26313..25b7ba774bd924 100755
--- a/libc/utils/docgen/docgen.py
+++ b/libc/utils/docgen/docgen.py
@@ -1,18 +1,16 @@
#!/usr/bin/env python3
-#
-# ====- Generate documentation for libc functions ------------*- python -*--==#
+# ===----------------------------------------------------------------------===##
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
-# ==-------------------------------------------------------------------------==#
+# ===----------------------------------------------------------------------===##
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import Dict
import os
import sys
-import yaml
from header import Header
@@ -77,7 +75,9 @@ def check_api(header: Header, api: Dict):
# Validate functions
if "functions" in api:
- if not header.fns_dir_exists():
+ if not header.fns_dir_exists() and not any(
+ header.implements_fn(f) for f in api["functions"]
+ ):
print(
f"warning: Function definitions are listed for {header.name}, but no function implementation directory exists at {header.fns_dir}. All functions will be listed as not implemented.",
file=sys.stderr,
@@ -93,11 +93,6 @@ def check_api(header: Header, api: Dict):
raise DocgenAPIFormatError("\n".join(errors))
-def load_api(header: Header) -> Dict:
- api = header.docgen_yaml.read_text(encoding="utf-8")
- return yaml.safe_load(api)
-
-
def print_tbl_dir(name):
print(
f"""
@@ -123,7 +118,7 @@ def print_functions_rst(header: Header, functions: Dict):
for name in sorted(functions.keys()):
print(f" * - {name}")
- if header.fns_dir_exists() and header.implements_fn(name):
+ if header.implements_fn(name):
print(" - |check|")
else:
print(" -")
@@ -206,7 +201,7 @@ def get_choices() -> list:
if path.parent != Path(__file__).parent:
fname = path.parent.name + os.sep + fname
choices.append(fname)
- return choices
+ return sorted(choices)
def parse_args() -> Namespace:
@@ -218,7 +213,6 @@ def parse_args() -> Namespace:
if __name__ == "__main__":
args = parse_args()
header = Header(args.header_name)
- api = load_api(header)
- check_api(header, api)
+ check_api(header, header.api)
- print_impl_status_rst(header, api)
+ print_impl_status_rst(header, header.api)
diff --git a/libc/utils/docgen/docgen_test.py b/libc/utils/docgen/docgen_test.py
new file mode 100644
index 00000000000000..9ee06b64bf2524
--- /dev/null
+++ b/libc/utils/docgen/docgen_test.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+# ===----------------------------------------------------------------------===##
+#
+# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+#
+# ===----------------------------------------------------------------------===##
+"""Unit tests for docgen and header implementation status evaluation."""
+
+from pathlib import Path
+import sys
+import tempfile
+import unittest
+
+sys.path.insert(0, str(Path(__file__).parent))
+from header import Header, _is_stub_file
+
+
+class DocgenTest(unittest.TestCase):
+ def test_header_stem(self):
+ self.assertEqual(Header("math.h").stem, "math")
+ self.assertEqual(Header("search.h").stem, "search")
+ self.assertEqual(Header("arpa/inet.h").stem, "arpa/inet")
+
+ def test_is_stub_file(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ stub = Path(tmpdir) / "stub.cpp"
+ stub.write_text(
+ "// TODO\n"
+ "LLVM_LIBC_FUNCTION(void *, s, ()) {\n"
+ " libc_errno = ENOSYS;\n"
+ " return nullptr;\n"
+ "}\n"
+ )
+ self.assertTrue(_is_stub_file(stub))
+
+ real = Path(tmpdir) / "real.cpp"
+ real.write_text("LLVM_LIBC_FUNCTION(int, r, (int x)) { return x + 1; }\n")
+ self.assertFalse(_is_stub_file(real))
+
+ def test_implements_fn(self):
+ self.assertTrue(Header("stdio.h").implements_fn("printf"))
+ self.assertFalse(Header("dlfcn.h").implements_fn("dlopen"))
+ self.assertFalse(Header("glob.h").implements_fn("glob"))
+ self.assertFalse(Header("nl_types.h").implements_fn("catopen"))
+ self.assertTrue(Header("netinet/in.h").implements_fn("htonl"))
+ self.assertTrue(Header("sys/time.h").implements_fn("select"))
+
+ def test_implements_macro(self):
+ self.assertTrue(Header("assert.h").implements_macro("assert"))
+ self.assertTrue(Header("errno.h").implements_macro("errno"))
+ self.assertTrue(Header("unistd.h").implements_macro("SEEK_SET"))
+ self.assertTrue(Header("float.h").implements_macro("NAN"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libc/utils/docgen/header.py b/libc/utils/docgen/header.py
index 8885db42f0a5b3..fa4437b69c7e27 100644
--- a/libc/utils/docgen/header.py
+++ b/libc/utils/docgen/header.py
@@ -1,12 +1,113 @@
-# ====- Information about standard headers used by docgen ----*- python -*--==#
+# ===----------------------------------------------------------------------===##
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
-# ==-------------------------------------------------------------------------==#
+# ===----------------------------------------------------------------------===##
from pathlib import Path
-from typing import Generator
+import re
+from typing import Dict, Generator, Optional, Set
+import yaml
+
+# Standard C freestanding headers (C23 4p6) provided directly by the compiler
+# (clang/lib/Headers/) rather than generated by LLVM-libc. When building with
+# Clang, their macros, types, and operations come from Clang's resource
+# headers, so docgen treats them as implemented even when no file exists under
+# libc/src/ or libc/include/llvm-libc-macros/.
+CLANG_FREESTANDING_HEADERS = {
+ "float.h",
+ "iso646.h",
+ "limits.h",
+ "stdalign.h",
+ "stdarg.h",
+ "stdatomic.h",
+ "stdbool.h",
+ "stdckdint.h",
+ "stddef.h",
+ "stdint.h",
+ "stdnoreturn.h",
+ "tgmath.h",
+}
+
+
+def _is_stub_file(path: Path) -> bool:
+ try:
+ text = path.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ return False
+ if "todo" not in text.lower() and "unimplemented" not in text.lower():
+ return False
+
+ idx = text.find("LLVM_LIBC_FUNCTION")
+ if idx == -1:
+ return False
+ open_brace = text.find("{", idx)
+ if open_brace == -1:
+ return False
+
+ depth, body = 0, ""
+ for i in range(open_brace, len(text)):
+ if text[i] == "{":
+ depth += 1
+ elif text[i] == "}":
+ depth -= 1
+ if depth == 0:
+ body = text[open_brace + 1 : i]
+ break
+
+ clean = re.sub(r"//.*$", "", body, flags=re.MULTILINE)
+ clean = re.sub(r"/\*.*?\*/", "", clean, flags=re.DOTALL).strip()
+ stmts = [s.strip() for s in clean.split(";") if s.strip()]
+ if len(stmts) == 0:
+ return True
+ if len(stmts) > 2:
+ return False
+
+ for stmt in stmts:
+ if stmt.startswith(("libc_errno =", "return")):
+ no_cast = re.sub(
+ r"(const_cast|reinterpret_cast|static_cast)\s*<[^>]+>", "", stmt
+ )
+ if "::" in no_cast:
+ return False
+ ret = no_cast.replace("return", "").strip()
+ if re.search(r"\b[A-Za-z0-9_]+\s*\(", ret):
+ return False
+ else:
+ return False
+ return True
+
+
+_IMPLEMENTED_FUNCTIONS: Optional[Set[str]] = None
+
+
+def _load_implemented_functions(libc_root: Path) -> Set[str]:
+ global _IMPLEMENTED_FUNCTIONS
+ if _IMPLEMENTED_FUNCTIONS is not None:
+ return _IMPLEMENTED_FUNCTIONS
+
+ stubs, reals = set(), set()
+ src_dir = libc_root / "src"
+ if src_dir.exists():
+ for p in src_dir.rglob("*.cpp"):
+ (stubs if _is_stub_file(p) else reals).add(p.stem)
+
+ stub_only = stubs - reals
+ _IMPLEMENTED_FUNCTIONS = set()
+ config_dir = libc_root / "config"
+ if config_dir.exists():
+ for ep_file in config_dir.rglob("entrypoints.txt"):
+ try:
+ for line in ep_file.read_text(encoding="utf-8").splitlines():
+ line = line.strip()
+ if line.startswith("libc.src."):
+ sym = line.split(".")[-1]
+ if sym not in stub_only:
+ _IMPLEMENTED_FUNCTIONS.add(sym)
+ except Exception:
+ pass
+ return _IMPLEMENTED_FUNCTIONS
class Header:
@@ -16,22 +117,16 @@ class Header:
* where is its macros file
* where is its docgen yaml file
- By convention, the macro-only part of a header file is in a header-specific
- file somewhere in the directory tree with root at
- ``$LLVM_PROJECT_ROOT/libc/include/llvm-libc-macros``. Docgen expects that
- if a macro is implemented, that it appears in a string
- ``#define MACRO_NAME`` in some ``*-macros.h`` file in the directory tree.
- Docgen searches for this string in the file to set the implementation status
- shown in the generated rst docs rendered as html for display at
- <libc.llvm.org>.
-
- By convention, each function for a header is implemented in a function-specific
- cpp file somewhere in the directory tree with root at, e.g,
- ``$LLVM_PROJECT_ROOT/libc/src/fenv``. Some headers have architecture-specific
- implementations, like ``math``, and some don't, like ``fenv``. Docgen uses the
- presence of this function-specific cpp file to set the implementation status
- shown in the generated rst docs rendered as html for display at
- <libc.llvm.org>.
+ Macro implementation status is checked across header-specific
+ ``*-macros.h`` files under ``$LLVM_PROJECT_ROOT/libc/include/llvm-libc-macros``,
+ macro and enum entries in ``$LLVM_PROJECT_ROOT/libc/include/<header>.yaml``
+ (including shared ``macro_header`` definitions), ``include/<header>.h.def``
+ templates, and compiler-provided freestanding headers.
+
+ Function implementation status is determined from the union of exported
+ entrypoints across ``$LLVM_PROJECT_ROOT/libc/config/**/entrypoints.txt``,
+ excluding source files under ``libc/src/`` whose only implementation is a
+ ``TODO`` stub.
"""
def __init__(self, header_name: str):
@@ -39,7 +134,7 @@ def __init__(self, header_name: str):
:param header_name: e.g., ``"threads.h"`` or ``"signal.h"``
"""
self.name = header_name
- self.stem = header_name.rstrip(".h")
+ self.stem = header_name[:-2] if header_name.endswith(".h") else header_name
self.docgen_root = Path(__file__).parent
self.libc_root = self.docgen_root.parent.parent
self.docgen_yaml = self.docgen_root / Path(header_name).with_suffix(".yaml")
@@ -50,31 +145,43 @@ def __init__(self, header_name: str):
self.fns_dir = Path(self.libc_root, "src", self.stem)
self.macros_dir = Path(self.libc_root, "include", "llvm-libc-macros")
+ def is_clang_provided(self) -> bool:
+ return self.name in CLANG_FREESTANDING_HEADERS
+
+ @property
+ def api(self) -> Dict:
+ if not hasattr(self, "_api"):
+ self._api = (
+ yaml.safe_load(self.docgen_yaml.read_text(encoding="utf-8"))
+ if self.docgen_yaml.exists()
+ else {}
+ ) or {}
+ return self._api
+
+ @property
+ def include_data(self) -> Dict:
+ if not hasattr(self, "_include_data"):
+ self._include_data = (
+ yaml.safe_load(self.include_yaml.read_text(encoding="utf-8"))
+ if self.include_yaml.exists()
+ else {}
+ ) or {}
+ return self._include_data
+
def macro_file_exists(self) -> bool:
- for _ in self.__get_macro_files():
+ if self.is_clang_provided() or any(self.__get_macro_files()):
return True
-
- if self.include_yaml.exists():
- import yaml
-
- parsed = yaml.safe_load(self.include_yaml.read_text(encoding="utf-8"))
- if (
- parsed
- and "macros" in parsed
- and any("macro_value" in m for m in parsed["macros"])
- ):
- return True
-
- return False
+ if (self.libc_root / "include" / f"{self.name}.def").exists():
+ return True
+ return bool(self.include_data.get("macros"))
def fns_dir_exists(self) -> bool:
return self.fns_dir.exists() and self.fns_dir.is_dir()
def implements_fn(self, fn_name: str) -> bool:
- for _ in self.fns_dir.glob(f"**/{fn_name}.cpp"):
+ if self.is_clang_provided():
return True
-
- return False
+ return fn_name in _load_implemented_functions(self.libc_root)
def implements_macro(self, m_name: str) -> bool:
"""
@@ -86,18 +193,31 @@ def implements_macro(self, m_name: str) -> bool:
:param m_name: name of macro, e.g., ``FE_ALL_EXCEPT``
"""
+ if self.is_clang_provided():
+ return True
+
for f in self.__get_macro_files():
- if f"#define {m_name}" in f.read_text():
- return True
+ try:
+ if f"#define {m_name}" in f.read_text(encoding="utf-8"):
+ return True
+ except Exception:
+ pass
+
+ if any(
+ m.get("macro_name") == m_name
+ and ("macro_value" in m or "macro_header" in m)
+ for m in self.include_data.get("macros", [])
+ ):
+ return True
- if self.include_yaml.exists():
- import yaml
+ if any(e.get("name") == m_name for e in self.include_data.get("enums", [])):
+ return True
- parsed = yaml.safe_load(self.include_yaml.read_text(encoding="utf-8"))
- if parsed and "macros" in parsed:
- for macro in parsed["macros"]:
- if macro.get("macro_name") == m_name and "macro_value" in macro:
- return True
+ def_file = self.libc_root / "include" / f"{self.name}.def"
+ if def_file.exists() and f"#define {m_name}" in def_file.read_text(
+ encoding="utf-8"
+ ):
+ return True
return False
``````````
</details>
https://github.com/llvm/llvm-project/pull/238908
More information about the libc-commits
mailing list