Files
json/docs/mkdocs/scripts/check_structure.py
Niels Lohmann 791cd88dfc Fix raw-TeX formulas and other documentation infrastructure debt (#5736)
* Fix math formulas rendering as raw TeX in the published docs

The privacy plugin self-hosts MathJax 2.7.0 but drops its
?config=TeX-MML-AM_CHTML query string, so the rehosted script loads no
input jax and the 10 formulas across 6 pages render as raw TeX to
readers. Remove pymdownx.arithmatex and the MathJax extra_javascript
entry, and rewrite the formulas in plain HTML (<sup>, <i>) instead.
This also drops a nine-year-old third-party script from every page.

Part of #5718

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix publish_documentation triggers and persist unneeded git credentials

publish_documentation.yml only triggered on docs/mkdocs/** pushes, but
the site also embeds .github/CODE_OF_CONDUCT.md, CONTRIBUTING.md,
SECURITY.md, cmake/{clang,gcc}_flags.cmake, .clang-tidy,
tools/astyle/.astylerc and tests/fmt_formatter/project/main.cpp via
pymdownx.snippets, so changes to those files never republished the
site. Extend the path filter to cover them, and switch runs-on from
the long-pinned ubuntu-22.04 to ubuntu-latest to match
ci_test_documentation.

Also add persist-credentials: false to the checkouts in ci_icpx and
ci_nvhpc (ubuntu.yml) and msvc-vs2026/msvc-arm64 (windows.yml), none
of which pushes with git, matching every other checkout in these
workflows.

Part of #5718

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix example build: broken debug echo, deprecations hidden for everything

docs/Makefile's debug echo used a space instead of a comma in
$(call cxx_standard ...), so it always printed an empty standard.
Every example was also compiled with -Wno-deprecated-declarations,
which would silently hide an accidental deprecated-API call in any of
them. Factor the duplicated compile flags into EXAMPLE_CPPFLAGS/
EXAMPLE_WARNFLAGS, build with -Werror=deprecated-declarations by
default, and only allow the three examples that intentionally
document deprecated API (the DEPRECATED_EXAMPLES list) to suppress it.

Part of #5718

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix check_structure.py NOLINT parsing and an off-by-one report line

`line.strip("<!-- NOLINT")` followed by `.strip(" -->")` strips any of
the characters in those sets from both ends, not a literal prefix; it
only happened to work for "Examples". A NOLINT'd section name
starting with N, O, L, I or T (e.g. "Notes", "Template parameters",
"Iterator invalidation", "Literals") was silently mangled, so the
suppression did not apply and the checker could report a spurious
missing/misordered section. Parse the comment with a regex instead.
The same fragile strip() pattern was used for heading text; replace it
with a plain prefix slice. Also fix the admonition_title report, which
used the 0-based line index while every other report in the file uses
lineno+1.

Part of #5718

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix docset README's non-existent make target and stale fallback URL

The README told readers to run `make nlohmann_json.docset`, but the
Makefile's targets are `all`, `JSON_for_Modern_C++.docset` and
`install_docset_zeal`; the documented command has failed with "No
rule to make target" since #2967 (2021). Point the README at the real
target and folder name. Info.plist's DashDocSetFallbackURL also still
pointed at the old nlohmann.github.io/json/ URL instead of the
canonical https://json.nlohmann.me/ from mkdocs.yml's site_url.

Leave list_missing_pages/list_removed_paths alone: they may become
redundant once #5638's check_docset() lands, which is a follow-up.

Part of #5718

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Remove two leftover Doxygen-era .link files from the examples directory

parse__iterator_pair.link and parse__pointers.link each held only a
Wandbox "online" permalink from the old Doxygen docs. #3071 deleted
every other .link file in 2021; these two came in through a parallel
PR (#3100) and were never referenced by any page, script or config.

Part of #5718

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix MacPorts CMake example to include its own snippet files

The MacPorts "Example: CMake" block included
integration/homebrew/example.cpp and
integration/homebrew/CMakeLists.txt instead of the MacPorts files
right next to it, a copy-paste slip from the Homebrew section. Nothing
referenced integration/macports/CMakeLists.txt as a result. The page
rendered correctly only because the homebrew, macports and
vcpkg/CMakeLists.txt snippets are byte-identical, so a future edit to
the MacPorts files would not have shown up on the page.

Part of #5718 item 6

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Do not persist git credentials in publish_documentation's checkout

The checkout step in publish_documentation.yml left the default
persist-credentials: true, so GITHUB_TOKEN stayed writable in
.git/config for the rest of the job (zizmor's artipacked finding). The
Deploy documentation step authenticates through its own github_token
input to peaceiris/actions-gh-pages and does not push with the
checked-out credentials, so persist-credentials: false is safe here,
matching every other checkout in the workflow set.

Overlaps #5638, which edits this same checkout step (adds
fetch-depth: 0); expect a rebase conflict there.

Part of #5718 item 2

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Replace list_missing_pages/list_removed_paths with a comm(1)-based diff

The docset Makefile's list_missing_pages ran one sqlite3 query per
mkdocs page, and list_removed_paths nested a loop over all mkdocs pages
inside a loop over all docset index paths (O(n*m) shell iteration).
Issue #5718 item 5 suggested removing or reducing these targets once
#5638's check_docset() lands, but that PR is still open and covers only
API pages and macros, not the full page set these targets check.
Replace the loops with two sorted path lists (DOCSET_PAGE_PATHS from
mkdocs' markdown sources, DOCSET_INDEX_PATHS from the built docset
index) compared with a single comm(1) call each, verified to produce
output identical to the old loops against the current docSet.dsidx.

The sed expression used '#' as its delimiter, which GNU Make reads as
a comment character even inside a variable assignment, truncating the
line and orphaning the closing paren of $(shell ...) ("unterminated
call to function 'shell': missing ')'"). Use '@' as the delimiter
instead.

Part of #5718 item 5

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-09-30 22:15:20 +02:00

223 lines
10 KiB
Python
Executable File

#!/usr/bin/env python
import glob
import os.path
import re
import sys
import yaml
warnings = 0
def report(rule, location, description) -> None:
global warnings
warnings += 1
print(f'{warnings:3}. {location}: {description} [{rule}]')
def check_structure() -> None:
expected_sections = [
"Template parameters",
"Specializations",
"Iterator invalidation",
"Requirements",
"Member types",
"Member functions",
"Member variables",
"Static functions",
"Non-member functions",
"Literals",
"Helper classes",
"Parameters",
"Return value",
"Exception safety",
"Exceptions",
"Complexity",
"Possible implementation",
"Default definition",
"Notes",
"Examples",
"See also",
"Version history",
]
required_sections = [
"Examples",
"Version history",
]
files = sorted(glob.glob("api/**/*.md", recursive=True))
for file in files:
with open(file) as file_content:
section_idx = -1 # the index of the current h2 section
existing_sections = [] # the list of h2 sections in the file
in_initial_code_example = False # whether we are inside the first code example block
previous_line = None # the previous read line
h1sections = 0 # the number of h1 sections in the file
last_overload = 0 # the last seen overload number in the code example
documented_overloads = {} # the overloads that have been documented in the current block
current_section = None # the name of the current section
for lineno, original_line in enumerate(file_content.readlines()):
line = original_line.strip()
if line.startswith("# "):
h1sections += 1
# there should only be one top-level title
if h1sections > 1:
report("structure/unexpected_section", f"{file}:{lineno+1}", f'unexpected top-level title "{line}"')
h1sections = 1
# Overview pages should have a better title
if line == "# Overview":
report("style/title", f"{file}:{lineno+1}", 'overview pages should have a better title than "Overview"')
# lines longer than 160 characters are bad (unless they are tables)
if len(line) > 160 and "|" not in line:
report("whitespace/line_length", f"{file}:{lineno+1} ({current_section})", f"line is too long ({len(line)} vs. 160 chars)")
# sections in `<!-- NOLINT -->` comments are treated as present
nolint_match = re.match(r"<!--\s*NOLINT\s+(.*?)\s*-->", line)
if nolint_match:
current_section = nolint_match.group(1)
existing_sections.append(current_section)
# check if sections are correct
if line.startswith("## "):
# before starting a new section, check if the previous one documented all overloads
if current_section in documented_overloads and last_overload != 0:
if len(documented_overloads[current_section]) > 0 and len(documented_overloads[current_section]) != last_overload:
expected = list(range(1, last_overload+1))
undocumented = [x for x in expected if x not in documented_overloads[current_section]]
unexpected = [x for x in documented_overloads[current_section] if x not in expected]
if len(undocumented):
report("style/numbering", f"{file}:{lineno} ({current_section})", f'undocumented overloads: {", ".join([f"({x})" for x in undocumented])}')
if len(unexpected):
report("style/numbering", f"{file}:{lineno} ({current_section})", f'unexpected overloads: {", ".join([f"({x})" for x in unexpected])}')
current_section = line[3:]
existing_sections.append(current_section)
if current_section in expected_sections:
idx = expected_sections.index(current_section)
if idx <= section_idx:
report("structure/section_order", f"{file}:{lineno+1}", f'section "{current_section}" is in an unexpected order (should be before "{expected_sections[section_idx]}")')
section_idx = idx
elif "index.md" not in file: # index.md files may have a different structure
report("structure/unknown_section", f"{file}:{lineno+1}", f'section "{current_section}" is not part of the expected sections')
# collect the numbered items of the current section to later check if they match the number of overloads
if last_overload != 0 and not in_initial_code_example:
if len(original_line) and original_line[0].isdigit():
number = int(re.findall(r"^(\d+).", original_line)[0])
if current_section not in documented_overloads:
documented_overloads[current_section] = []
documented_overloads[current_section].append(number)
# code example
if line == "```cpp" and section_idx == -1:
in_initial_code_example = True
if in_initial_code_example and line.startswith("//") and line not in ["// since C++20", "// until C++20"]:
# check numbering of overloads
if any(map(str.isdigit, line)):
number = int(re.findall(r"\d+", line)[0])
if number != last_overload + 1:
report("style/numbering", f"{file}:{lineno+1}", f"expected number ({number}) to be ({last_overload +1 })")
last_overload = number
if any(map(str.isdigit, line)) and "(" not in line:
report("style/numbering", f"{file}:{lineno+1}", f"number should be in parentheses: {line}")
if line == "```" and in_initial_code_example:
in_initial_code_example = False
# consecutive blank lines are bad
if line == "" and previous_line == "":
report("whitespace/blank_lines", f"{file}:{lineno}-{lineno+1} ({current_section})", "consecutive blank lines")
# check that non-example admonitions have titles
untitled_admonition = re.match(r"^(\?\?\?|!!!) ([^ ]+)$", line)
if untitled_admonition and untitled_admonition.group(2) != "example":
report("style/admonition_title", f"{file}:{lineno+1} ({current_section})", f'"{untitled_admonition.group(2)}" admonitions should have a title')
previous_line = line
if "index.md" not in file: # index.md files may have a different structure
for required_section in required_sections:
if required_section not in existing_sections:
report("structure/missing_section", f"{file}:{lineno+1}", f'required section "{required_section}" was not found')
def check_examples() -> None:
example_files = sorted(glob.glob("../../examples/*.cpp"))
markdown_files = sorted(glob.glob("**/*.md", recursive=True))
# check if every example file is used in at least one markdown file
for example_file in example_files:
example_file = os.path.join("examples", os.path.basename(example_file))
found = False
for markdown_file in markdown_files:
content = " ".join(open(markdown_file).readlines())
if example_file in content:
found = True
break
if not found:
report("examples/missing", f"{example_file}", "example file is not used in any documentation file")
def check_links() -> None:
"""Check that every entry in the navigation (nav in mkdocs.yml) links to at most one file. If a file is linked more
than once, then the first entry is repeated. See https://github.com/nlohmann/json/issues/4564 for the issue in
this project and https://github.com/mkdocs/mkdocs/issues/3428 for the root cause.
The issue can be fixed by merging the keys, so
- 'NLOHMANN_JSON_VERSION_MAJOR': api/macros/nlohmann_json_version_major.md
- 'NLOHMANN_JSON_VERSION_MINOR': api/macros/nlohmann_json_version_major.md
would be replaced with
- 'NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR': api/macros/nlohmann_json_version_major.md
"""
file_with_path = {}
def collect_links(node, path="") -> None:
if isinstance(node, list):
for x in node:
collect_links(x, path)
elif isinstance(node, dict):
for p, x in node.items():
collect_links(x, path + "/" + p)
else:
if node not in file_with_path:
file_with_path[node] = []
file_with_path[node].append(path)
with open("../mkdocs.yml") as mkdocs_file:
# see https://github.com/yaml/pyyaml/issues/86#issuecomment-1042485535
yaml.add_multi_constructor("tag:yaml.org,2002:python/name", lambda loader, suffix, node: None, Loader=yaml.SafeLoader)
yaml.add_multi_constructor("!ENV", lambda loader, suffix, node: None, Loader=yaml.SafeLoader)
y = yaml.safe_load(mkdocs_file)
collect_links(y["nav"])
for duplicate_file in [x for x in file_with_path if len(file_with_path[x]) > 1]:
file_list = [f'"{x}"' for x in file_with_path[duplicate_file]]
file_list_str = ", ".join(file_list)
report("nav/duplicate_files", "mkdocs.yml", f'file "{duplicate_file}" is linked with multiple keys in "nav": {file_list_str}; only one is rendered properly, see #4564')
if __name__ == "__main__":
print(120 * "-")
check_structure()
check_examples()
check_links()
print(120 * "-")
if warnings > 0:
sys.exit(1)