[libc-commits] [libc] 9f81d32 - [libc][docs] Check entrypoints and filter stubs in docgen (#238908)

via libc-commits libc-commits at lists.llvm.org
Thu Nov 5 12:57:04 PST 2026


Author: Jeff Bailey
Date: 2026-11-05T20:56:58Z
New Revision: 9f81d32df0f9fdd95a087cde6ad9af4c6b9a6168

URL: https://github.com/llvm/llvm-project/commit/9f81d32df0f9fdd95a087cde6ad9af4c6b9a6168
DIFF: https://github.com/llvm/llvm-project/commit/9f81d32df0f9fdd95a087cde6ad9af4c6b9a6168.diff

LOG: [libc][docs] Check entrypoints and filter stubs in docgen (#238908)

docgen previously checked for matching .cpp and *-macros.h files to mark
symbols as implemented.  That counted ENOSYS placeholder stubs as
complete while missing shared entrypoints, Clang freestanding headers,
and macros defined in hdrgen YAML or .h.def templates.

Check exported entrypoints.txt symbols scoped to each header (excluding
TODO stubs) for functions, and include hdrgen YAML, .h.def templates,
and freestanding headers for macros.  Point Furo View and Edit links on
generated pages to their docgen YAML definitions instead of build-tree
paths.

Assisted-by: Automated tooling, human reviewed.

Added: 
    libc/utils/docgen/docgen_test.py

Modified: 
    libc/docs/conf.py
    libc/docs/dev/building_docs.md
    libc/utils/docgen/docgen.py
    libc/utils/docgen/header.py

Removed: 
    


################################################################################
diff  --git a/libc/docs/conf.py b/libc/docs/conf.py
index 5477861c7bb181..f914a0bb2a20af 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..f6172cd1c26fb6 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
 
@@ -62,7 +60,9 @@ def check_api(header: Header, api: Dict):
 
     # Validate macros
     if "macros" in api:
-        if not header.macro_file_exists():
+        if not header.macro_file_exists() and not any(
+            header.implements_macro(m) for m in api["macros"]
+        ):
             print(
                 f"warning: Macro definitions are listed for {header.name}, but no macro file can be found in the directory tree rooted at {header.macros_dir}. All macros will be listed as not implemented.",
                 file=sys.stderr,
@@ -77,7 +77,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 +95,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 +120,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("    -")
@@ -165,7 +162,7 @@ def print_macros_rst(header: Header, macros: Dict):
     for name in sorted(macros.keys()):
         print(f"  * - {name}")
 
-        if header.macro_file_exists() and header.implements_macro(name):
+        if header.implements_macro(name):
             print("    - |check|")
         else:
             print("    -")
@@ -206,7 +203,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 +215,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..6b1048edd13ed7
--- /dev/null
+++ b/libc/utils/docgen/docgen_test.py
@@ -0,0 +1,77 @@
+#!/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.assertTrue(Header("netinet/in.h").implements_fn("htonl"))
+        self.assertFalse(Header("stdio.h").implements_fn("sqrt"))
+        self.assertFalse(Header("math.h").implements_fn("printf"))
+
+        with tempfile.TemporaryDirectory() as tmpdir:
+            root = Path(tmpdir)
+            src = root / "src" / "foo"
+            cfg = root / "config" / "linux"
+            src.mkdir(parents=True)
+            cfg.mkdir(parents=True)
+            (src / "stub_fn.cpp").write_text(
+                "// TODO\nLLVM_LIBC_FUNCTION(int, stub_fn, ()) { return -1; }\n"
+            )
+            (src / "real_fn.cpp").write_text(
+                "LLVM_LIBC_FUNCTION(int, real_fn, (int x)) { return x + 1; }\n"
+            )
+            (cfg / "entrypoints.txt").write_text(
+                "libc.src.foo.stub_fn\nlibc.src.foo.real_fn\n"
+            )
+            hdr = Header("foo.h", libc_root=root)
+            self.assertFalse(hdr.implements_fn("stub_fn"))
+            self.assertTrue(hdr.implements_fn("real_fn"))
+
+    def test_implements_macro(self):
+        self.assertTrue(Header("assert.h").implements_macro("assert"))
+        self.assertFalse(Header("sys/syscall.h").macro_file_exists())
+        self.assertTrue(Header("sys/syscall.h").implements_macro("SYS_read"))
+        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..9d9beb492a7ede 100644
--- a/libc/utils/docgen/header.py
+++ b/libc/utils/docgen/header.py
@@ -1,12 +1,120 @@
-# ====- 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 functools import lru_cache
 from pathlib import Path
-from typing import Generator
+import re
+from typing import Dict, Generator, Optional, Set, Tuple
+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:
+    text = path.read_text(encoding="utf-8")
+    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
+
+
+ at lru_cache(maxsize=None)
+def _load_implemented_functions(
+    libc_root: Path,
+) -> Tuple[Set[str], Dict[str, Set[str]]]:
+    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
+    all_fns: Set[str] = set()
+    by_stem: Dict[str, Set[str]] = {}
+    config_dir = libc_root / "config"
+    if config_dir.exists():
+        for ep_file in config_dir.rglob("entrypoints.txt"):
+            for line in ep_file.read_text(encoding="utf-8").splitlines():
+                line = line.strip()
+                if line.startswith("libc.src."):
+                    parts = line.split(".")
+                    sym = parts[-1]
+                    if sym not in stub_only:
+                        all_fns.add(sym)
+                        stem = "/".join(parts[2:-1])
+                        by_stem.setdefault(stem, set()).add(sym)
+    return all_fns, by_stem
+
+
+def _load_include_yaml(yaml_path: Path) -> Dict:
+    if not yaml_path.exists():
+        return {}
+    data = yaml.safe_load(yaml_path.read_text(encoding="utf-8")) or {}
+    for rel in data.get("merge_yaml_files", []):
+        merged = _load_include_yaml((yaml_path.parent / rel).resolve())
+        for key in ("macros", "types", "enums", "objects", "functions"):
+            if key in merged:
+                data.setdefault(key, []).extend(merged[key])
+    return data
 
 
 class Header:
@@ -16,32 +124,28 @@ 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):
+    def __init__(self, header_name: str, libc_root: Optional[Path] = None):
         """
         :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.libc_root = (
+            libc_root if libc_root is not None else self.docgen_root.parent.parent
+        )
         self.docgen_yaml = self.docgen_root / Path(header_name).with_suffix(".yaml")
         # Path to libc/include/<name>.yaml
         self.include_yaml = Path(
@@ -50,31 +154,44 @@ 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 = _load_include_yaml(self.include_yaml)
+        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
+        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
+        all_fns, by_stem = _load_implemented_functions(self.libc_root)
+        if fn_name in by_stem.get(self.stem, set()):
+            return True
+        if not hasattr(self, "_declared_fns"):
+            self._declared_fns = {
+                f["name"] for f in self.include_data.get("functions", []) if "name" in f
+            }
+        return fn_name in all_fns and fn_name in self._declared_fns
 
     def implements_macro(self, m_name: str) -> bool:
         """
@@ -86,18 +203,28 @@ 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():
+            if f"#define {m_name}" in f.read_text(encoding="utf-8"):
                 return True
 
-        if self.include_yaml.exists():
-            import yaml
+        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 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
 


        


More information about the libc-commits mailing list