From 75f10689e9b39bc5fc3e3f6114aab1931481576b Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 11:09:52 -0300 Subject: [PATCH 01/59] asio and cobalt: their tests and texts under the -O3 release link --- libs/asio | 2 +- libs/cobalt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/asio b/libs/asio index 6c4e2c85..bbc81f55 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 6c4e2c85fe6e875bbf67db095df2497b93bf455b +Subproject commit bbc81f55721b1a67f6bc96961c0bdf5496a681a7 diff --git a/libs/cobalt b/libs/cobalt index 5d51c4aa..79da1f68 160000 --- a/libs/cobalt +++ b/libs/cobalt @@ -1 +1 @@ -Subproject commit 5d51c4aa89e563070aa244e0635139758d762f97 +Subproject commit 79da1f6803df549aea8ddc7683d65ee459f3a6bc From 03bb7cb8d2c3a311e462601db23bca7233bce396 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 11:23:43 -0300 Subject: [PATCH 02/59] guidelines: asio's Asyncify stack and published sizes under the -O3 release link --- CODING-GUIDELINES.md | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 85fc6723..3316c841 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -6491,11 +6491,15 @@ Asio's first library-main CI and the final joint candidate remain separate gates - **Asyncify's stack is 8192 bytes unless a program raises it with the propagated feature `asyncify-stack-size` (powers of two up to 1048576, a smaller value stopping the compile), and `asyncify_stack` reads the bytes - each unwind wrote from Asyncify's own data, in debug, release and release - linked with `-O3`.** A suspension that does not fit traps with - `RuntimeError: unreachable`; 8192 is twice the smallest power of two every - build passed with (deepest 3,540 bytes, Cobalt's 1,088), and Emscripten's - default of 4096 left 556 bytes. + each unwind wrote from Asyncify's own data, in debug and release.** A + suspension that does not fit traps with `RuntimeError: unreachable`. 8192 + was twice the smallest power of two every build passed with when b2 linked + a release build without optimization (deepest 3,540 bytes, Cobalt's + 1,088); since release links at `-O3` (#18) debug is the deepest build + (1,168 bytes, 388 in release; Cobalt's 1,036 and 384, measured on + 2026-11-15), and 8192 stays the default and the floor that the libraries + built on asio and their programs are tested against, a smaller one being a + change of its own to measure across them. Source: `genesis/design.md`, D5 (proposals); `AGENTS.md` (asio). - **Artifacts are named Boost's way (`app-60-d-jspi.js`, `webcpp-suspend-asyncify/app-60-d-asyncify.js`), `webcpp.variants` builds a @@ -6507,10 +6511,13 @@ Asio's first library-main CI and the final joint candidate remain separate gates `response.url`, so that a redirect does not misdirect it. Source: `genesis/design.md`, D10, and `genesis/reference/STATUS.md`, task 12 (proposals). -- **Published binary sizes are release builds linked with `-O3` explicitly, - and `webcpp.size-table` records every guide example in both variants.** b2's - emscripten toolset does not pass the optimization level to the link; in - release Asyncify's program is about 1.9 times JSPI's (2.9 in debug). The +- **Published binary sizes are release builds, which the superproject links + at `-O3` as it compiles them, and `webcpp.size-table` records every guide + example in both variants.** b2 1.92's emscripten toolset passes no + optimization level to the link, which the Jamroot's region + `emscripten-link-optimization` adds (#18); in release Asyncify's program + is about twice JSPI's (asio's timers, 988,047 bytes against 489,216 of + `.wasm`), and 2.9 times in debug. The optimized JSPI link exports `emscripten_stack_get_current` and `_emscripten_stack_restore`, since Emscripten reads `EM_JS_DEPS` after native linking. From a60e6fe72c3a2e06911329304319248df4eb5dfc Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 12:00:41 -0300 Subject: [PATCH 03/59] asio: the Asyncify stack stays 8192, as the owner decided --- CODING-GUIDELINES.md | 8 +++++--- libs/asio | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 3316c841..307c7e0b 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -6497,9 +6497,11 @@ Asio's first library-main CI and the final joint candidate remain separate gates a release build without optimization (deepest 3,540 bytes, Cobalt's 1,088); since release links at `-O3` (#18) debug is the deepest build (1,168 bytes, 388 in release; Cobalt's 1,036 and 384, measured on - 2026-11-15), and 8192 stays the default and the floor that the libraries - built on asio and their programs are tested against, a smaller one being a - change of its own to measure across them. + 2026-11-15). The owner decided on 2026-11-15 that 8192 stays: programs + ship release builds, where the deepest suspension of the libraries built + on asio wrote 564 bytes (trystero's room test), and debug, for + development and the tests, 2,344, within the half `asyncify_stack` asks; + 8192 is also the floor those libraries are tested against. Source: `genesis/design.md`, D5 (proposals); `AGENTS.md` (asio). - **Artifacts are named Boost's way (`app-60-d-jspi.js`, `webcpp-suspend-asyncify/app-60-d-asyncify.js`), `webcpp.variants` builds a diff --git a/libs/asio b/libs/asio index bbc81f55..2a59df26 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit bbc81f55721b1a67f6bc96961c0bdf5496a681a7 +Subproject commit 2a59df26741b9fb1c498d0be35396ff424cbff59 From c66c95e2d74b8ab968ed70eb1399b1d4cf4c530a Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 18:13:50 -0300 Subject: [PATCH 04/59] Jamroot: third_party also as /third_party, the id a user's Jamfile writes --- CODING-GUIDELINES.md | 7 +++---- Jamroot | 5 +++++ doc/releases/0.1.0.adoc | 2 ++ tools/test/jamroot_test.py | 19 ++++++++++++++++--- 4 files changed, 26 insertions(+), 7 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 307c7e0b..7bee2900 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -895,7 +895,9 @@ owner's: What a library or its tests use and webcpp does not own is never copied into a library: it is a submodule under `third_party/libs/`, pinned at a commit, with the URL of its own repository, and `third_party/Jamfile` -declares it as `/webcpp/third_party//`, whose usage requirements +declares it. The Jamroot registers the project under both ids, +`/webcpp/third_party//` and `/third_party//`, the latter the +form a user's Jamfile writes (chapter 5, rule 5); the target's usage requirements give a program what it needs. It keeps its own licence and notices, and the lint never reads it (chapter 9). Adding one is the owner's decision; moving its pin is a change of its own, with its evidence. A target whose submodule @@ -8981,9 +8983,6 @@ These are errors of the rules' own text, moved here unchanged (the proposal (`libs/trystero/include/webcpp/trystero/config.hpp:14`). It also calls the specifications of asio and crypto "in review"; the owner accepted both on 2026-10-11. -- Chapter 10 registers the project `/webcpp/third_party` (`Jamroot`), while - chapter 5's rule 5 writes `/third_party//bearssl` and crypto's plan - `/third_party//`. - Chapter 8 lets a program exclude a target with `#ifndef __wasi__`, while config's design chose `WEBCPP_TARGET_*` so that no library reads the compiler's macros (config's genesis `design.md`); xactor's `drivers.hpp` diff --git a/Jamroot b/Jamroot index 8a36efd8..dc98774e 100644 --- a/Jamroot +++ b/Jamroot @@ -550,6 +550,11 @@ use-project /webcpp/doc-tools : tools/doc ; # under third_party/libs/ (third_party/Jamfile). use-project /webcpp/third_party : third_party ; +# The same project under the id a user's Jamfile writes, /third_party// +# (CODING-GUIDELINES.md chapter 5, "Bringing a C library into webcpp"): b2 +# resolves both ids to the one Jamfile. +use-project /third_party : third_party ; + # The files under directory, at any depth, without its directories, which # glob-tree-ex returns too, and without hidden files such as .DS_Store. rule files-under ( directory ) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 005503fb..8247746f 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -223,6 +223,8 @@ exceptions, such as an `asyncify` variant's. Emscripten's notice that the runtime is kept alive. * Changed the lint rule `bare-throw` to leave alone the JavaScript of an `EM_JS` function or an `EM_ASM` block. +* Added the project id /third_party, the form a user's Jamfile writes for third-party +code. [#webcpp-0-1-0-compilers-tested] == Compilers tested diff --git a/tools/test/jamroot_test.py b/tools/test/jamroot_test.py index e7718fe3..47b9d126 100755 --- a/tools/test/jamroot_test.py +++ b/tools/test/jamroot_test.py @@ -7,9 +7,9 @@ """Checks the Jamroot: it finds the installed Boost and searches it first, refuses a missing or older one by naming the fix, refuses one whose version it cannot read, checks again when Boost -changes, keeps Boost's warnings out of -Werror, refuses CPATH, and installs the headers. Each -case builds a scratch superproject with the fixture library demo. Run with the names of some -cases to run only those.""" +changes, keeps Boost's warnings out of -Werror, refuses CPATH, reaches third_party/ through both +of its project ids, and installs the headers. Each case builds a scratch superproject with the +fixture library demo. Run with the names of some cases to run only those.""" from __future__ import annotations @@ -216,6 +216,18 @@ def test_install_copies_headers_to_prefix(root): shutil.rmtree(prefix) +def test_third_party_has_both_ids(root): + # A user's Jamfile names /third_party// (CODING-GUIDELINES.md chapter 5, rule 5); + # the existing consumers name /webcpp/third_party//: both reach one project. The probe + # is appended to the real third_party/Jamfile, whose targets the Jamroot names. + with (root / 'third_party/Jamfile').open('a') as jamfile: + jamfile.write('\nalias probe : : : : WEBCPP_TEST_PROBE=1 ;\nexplicit probe ;\n') + harness.add_library(root, 'ids', 'alias one : /third_party//probe ;\n' + 'alias two : /webcpp/third_party//probe ;\n', {}) + result = harness.run_b2(root, '-n', 'libs/ids/test//one', 'libs/ids/test//two') + harness.expect(result, True) + + CASES = [ test_boost_found_and_fixture_builds, test_no_boost_configured_names_the_fix, @@ -228,6 +240,7 @@ def test_install_copies_headers_to_prefix(root): test_cpath_set_is_refused, test_a_relative_user_config_is_found, test_install_copies_headers_to_prefix, + test_third_party_has_both_ids, ] From 0dc9759e1b09f6f228d29ec70af26d664a0efae5 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:50:44 -0300 Subject: [PATCH 05/59] tools: the user's Jamfiles of webcpp::crypto as fixtures of a test of the tools --- CODING-GUIDELINES.md | 24 ++- doc/releases/0.1.0.adoc | 1 + tools/test/crypto_jamfiles_test.py | 178 ++++++++++++++++++ .../fixtures/crypto_jamfiles/broken/Jamfile | 7 + .../crypto_jamfiles/broken/broken.cpp | 9 + .../crypto_jamfiles/broken/broken.outcome | 9 + .../default_openssl_on_emscripten/Jamfile | 7 + .../default_openssl_on_emscripten/app.cpp | 9 + .../default_openssl_on_emscripten.outcome | 10 + .../has_openssl_on_emscripten/Jamfile | 7 + .../has_openssl_on_emscripten/app.cpp | 9 + .../has_openssl_on_emscripten.outcome | 10 + .../fixtures/crypto_jamfiles/hello/Jamfile | 7 + .../fixtures/crypto_jamfiles/hello/hello.cpp | 11 ++ .../crypto_jamfiles/hello/hello.outcome | 11 ++ 15 files changed, 308 insertions(+), 1 deletion(-) create mode 100644 tools/test/crypto_jamfiles_test.py create mode 100644 tools/test/fixtures/crypto_jamfiles/broken/Jamfile create mode 100644 tools/test/fixtures/crypto_jamfiles/broken/broken.cpp create mode 100644 tools/test/fixtures/crypto_jamfiles/broken/broken.outcome create mode 100644 tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/Jamfile create mode 100644 tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/app.cpp create mode 100644 tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome create mode 100644 tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/Jamfile create mode 100644 tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/app.cpp create mode 100644 tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome create mode 100644 tools/test/fixtures/crypto_jamfiles/hello/Jamfile create mode 100644 tools/test/fixtures/crypto_jamfiles/hello/hello.cpp create mode 100644 tools/test/fixtures/crypto_jamfiles/hello/hello.outcome diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 7bee2900..4e353bdd 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -100,7 +100,8 @@ Not built yet: changed: `tools/test/jamroot_test.py`, `tools/test/webcpp_jam_test.py`, `tools/test/oracle_jam_test.py`, `tools/test/generated_jam_test.py`, `tools/test/component_jam_test.py`, `tools/generated/generated_test.py`, - `tools/test/emscripten_test.py`, `tools/test/external_test.py`, + `tools/test/emscripten_test.py`, `tools/test/crypto_jamfiles_test.py`, + `tools/test/external_test.py`, `tools/test/doc_test.py`, `tools/test/harness_test.py`, `tools/test/third_party_test.py`, `tools/test/boost_libraries_test.py`, @@ -574,6 +575,27 @@ aliases, concepts, variables, data members and macros. build is excluded by declaration (`: native`), and inside a program by the same condition the library uses (`#ifndef __wasi__`), never by skipping silently. +- A user's Jamfile of a library whose own tests cannot express it (b2's raw + `exe`, a refusal on one target) is a fixture of the tools' test, not a + library's test: `tools/test/fixtures/crypto_jamfiles//` holds the + case's `Jamfile`, its sources and `.outcome`, and + `tools/test/crypto_jamfiles_test.py` builds each case on a scratch + superproject, with b2 as a user runs it, once per target, in a build + directory the cases of a target share. The outcome file's lines starting + with `#` are comments; a block `[all]`, `[native]`, `[native-linux]`, + `[native-darwin]`, `[native-windows]`, `[wasip2]`, `[wasip3]` or + `[emscripten]` applies by the target and the system (`[all]` and each block + that matches apply). `targets: ...` (native only without it) names + the targets the case is built for; `build: succeeds` or `build: fails` is + b2's exit status; after `build: fails` every other line must appear whole in + b2's output, in any order; `run: `, after `build: succeeds`, runs + the program as its lane runs one and every other line is its standard + output, exactly; `arguments: ...` gives b2 words for this case alone + (`@scratch` is the case's scratch directory). The fixtures sit outside + `libs/*/test/`, so the raw-rules lint does not apply to them. The tools job + of the CI runs the test; the `[native-darwin]` blocks apply only to a run on + macOS, and the MSVC cases are `webcpp.compile-fail` and `webcpp.link-fail` + of the library's tests. - A test moved from the original's or another suite records the conversion, case by case, and each converted case is seen failing on a planted defect where the old one had a pinning test (`libs/xactor/test/CONVERSION.md`). diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 8247746f..926309df 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -66,6 +66,7 @@ None. * Fixed driven-test execution and descendant cleanup on Windows. * Fixed driven-test executable reuse for Windows and WASI builds. * Improved lint preparation by separating OpenSSL headers from archive builds and upstream tests. +* Added the user's Jamfiles of webcpp::crypto, tested as fixtures of a test of the tools. * Fixed the WASIp2 test launcher interrupting large finite workloads after 60 seconds. * Fixed Chrome provisioning and browser/TLS profile coverage in Asio CI lanes. * Added source-built OpenSSL and Cobalt SSL targets for WASIp2. diff --git a/tools/test/crypto_jamfiles_test.py b/tools/test/crypto_jamfiles_test.py new file mode 100644 index 00000000..3ff1c2d8 --- /dev/null +++ b/tools/test/crypto_jamfiles_test.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Builds every fixture of tools/test/fixtures/crypto_jamfiles, a Jamfile as a user of +webcpp::crypto writes it (b2's raw exe), with b2 as a user runs it, and checks its outcome file: +the build's status, the lines a failure prints, and a program's output (CODING-GUIDELINES.md +chapter 8). One scratch superproject per target, with libs/crypto and the fixtures in it; every +case of a target shares one build directory, so BearSSL's 295 files are compiled once per +target. Run with the names of some cases to run only those, and with --target to run one +target.""" + +from __future__ import annotations + +import platform +import shutil +import subprocess +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path + +import harness + +CASES = harness.FIXTURES / 'crypto_jamfiles' +TOOLSETS = {'native': [], 'wasip2': ['toolset=clang-wasip2'], 'wasip3': ['toolset=clang-wasip3'], + 'emscripten': ['toolset=emscripten']} +SYSTEM = {'Linux': 'linux', 'Darwin': 'darwin', 'Windows': 'windows'}[platform.system()] + +# Cases whose outcome needs code that is not merged yet; a run without names leaves them out, +# a run that names one builds it. Each entry names what it waits for. +NOT_YET = { + 'has_openssl_on_emscripten': 'the refusal in config.hpp (Task 6)', + 'default_openssl_on_emscripten': 'the refusal in config.hpp (Task 6)', +} + + +def launcher(target: str) -> Path: + """The script the lanes run a WASI program with (tools/ci/matrix.py, wasm_lane).""" + return harness.ROOT / f'tools/boost/asio-{target}/run.sh' + + +@dataclass +class Outcome: + """What an outcome file says for one target.""" + targets: list[str] = field(default_factory=lambda: ['native']) + succeeds: bool = True + run: str | None = None + lines: list[str] = field(default_factory=list) + arguments: list[str] = field(default_factory=list) + + +def outcome(path: Path, target: str) -> Outcome: + """The blocks of path that apply to target on this system, read into an Outcome.""" + applying = {'all', target} | ({'native', 'native-' + SYSTEM} if target == 'native' else set()) + result = Outcome() + block = None + for raw in path.read_text().splitlines(): + if not raw.strip() or raw.startswith('#'): + continue + if raw.startswith('[') and raw.endswith(']'): + block = raw[1:-1] + continue + if block is None: + raise SystemExit(f'{path}: a line before the first [block]: {raw!r}') + if block not in applying: + continue + key, _, value = raw.partition(': ') + if key == 'targets': + result.targets = value.split() + elif key == 'build': + result.succeeds = value == 'succeeds' + elif key == 'run': + result.run = value + elif key == 'arguments': + result.arguments += value.split() + else: + result.lines.append(raw) + return result + + +def program_command(build_dir: Path, case: str, name: str, target: str) -> list[str]: + """The command that runs the program name that the build of case made under build_dir, as its + lane runs one.""" + suffix = {'native': '.exe' if SYSTEM == 'windows' else '', 'wasip2': '.wasm', + 'wasip3': '.wasm', 'emscripten': '.js'}[target] + found = [p for p in build_dir.rglob(name + suffix) + if p.is_file() and f'user/{case}/' in p.relative_to(build_dir).as_posix() + '/'] + if len(found) != 1: + raise AssertionError(f'the build made {len(found)} files named {name}{suffix}') + if target == 'emscripten': + return ['node', str(found[0])] + if target.startswith('wasi'): + return [str(launcher(target)), str(found[0])] + return [str(found[0])] + + +def selected(names: list[str], target: str) -> list[Path]: + """The case directories to build for target: the named ones, else every one that is not in + NOT_YET, each that its outcome file's targets line names target for.""" + cases = [] + for case in sorted(p.parent for p in CASES.glob('*/*.outcome')): + if (names and case.name not in names) or (not names and case.name in NOT_YET): + continue + if target in outcome(next(case.glob('*.outcome')), target).targets: + cases.append(case) + return cases + + +def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: + """Builds each of cases for target in root and returns the faults, one line each.""" + faults: list[str] = [] + build_dir = root / 'bin' / f'user-{target}' + for case in cases: + expected = outcome(next(case.glob('*.outcome')), target) + scratch = root / 'scratch' / case.name + scratch.mkdir(parents=True, exist_ok=True) + arguments = [a.replace('@scratch', str(scratch)) for a in expected.arguments] + launch = [f'testing.launcher={launcher(target)}'] if target.startswith('wasi') else [] + built = harness.run_b2(root, f'--build-dir={build_dir}', *TOOLSETS[target], *launch, + *arguments, f'user/{case.name}') + output = built.stdout + if (built.returncode == 0) != expected.succeeds: + faults.append(f'{case.name} on {target}: the build ' + f'{"succeeded" if built.returncode == 0 else "failed"}\n{output[-3000:]}') + continue + if not expected.succeeds: + faults += [f'{case.name} on {target}: b2 did not print: {line}' + for line in expected.lines if line not in output] + continue + if expected.run is not None: + command = program_command(build_dir, case.name, expected.run, target) + ran = subprocess.run(command, capture_output=True, text=True, check=False) + printed = ran.stdout.replace('\r\n', '\n').splitlines() + if ran.returncode != 0 or printed != expected.lines: + faults.append(f'{case.name} on {target}: {expected.run} exited {ran.returncode} ' + f'and printed {printed!r}; the outcome says {expected.lines!r}') + return faults + + +def main(argv: list[str]) -> int: + targets = list(TOOLSETS) + if '--target' in argv: + targets = [argv[argv.index('--target') + 1]] + argv = [a for a in argv if a not in ('--target', targets[0])] + if targets[0] not in TOOLSETS: + raise SystemExit(f'crypto_jamfiles: no target {targets[0]}; ' + f'the targets are {list(TOOLSETS)}') + names = [a for a in argv if not a.startswith('--')] + faults: list[str] = [] + for target in targets: + cases = selected(names, target) + if not cases: + continue + started = time.monotonic() + root = harness.scratch_superproject() + try: + harness.copy_integration_libraries(root, 'crypto') + shutil.copytree(CASES, root / 'user', ignore=harness.built) + if target == 'emscripten': + harness.link_emsdk(root) + elif target.startswith('wasi'): + harness.link_wasi_tools(root) + faults += run_target(root, target, cases) + finally: + shutil.rmtree(root) + print(f'{target}: done in {time.monotonic() - started:.0f} s') + for fault in faults: + print(f'crypto_jamfiles: {fault}', file=sys.stderr) + print('crypto_jamfiles_test: ' + ('failed' if faults else 'ok')) + return 1 if faults else 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/test/fixtures/crypto_jamfiles/broken/Jamfile b/tools/test/fixtures/crypto_jamfiles/broken/Jamfile new file mode 100644 index 00000000..3aba4fed --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/broken/Jamfile @@ -0,0 +1,7 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +exe broken : broken.cpp ; diff --git a/tools/test/fixtures/crypto_jamfiles/broken/broken.cpp b/tools/test/fixtures/crypto_jamfiles/broken/broken.cpp new file mode 100644 index 00000000..38699138 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/broken/broken.cpp @@ -0,0 +1,9 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#error "broken on purpose" + +int main() {} diff --git a/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome b/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome new file mode 100644 index 00000000..f9a0111f --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +build: fails +broken on purpose diff --git a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..8e0ba649 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/Jamfile @@ -0,0 +1,7 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +exe app : app.cpp /webcpp/crypto//crypto : WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL ; diff --git a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..6c80fb35 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/app.cpp @@ -0,0 +1,9 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include + +int main() {} diff --git a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome new file mode 100644 index 00000000..af5f9f9f --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome @@ -0,0 +1,10 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: emscripten +build: fails +webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define, or make it WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL. diff --git a/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..77e3cad6 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/Jamfile @@ -0,0 +1,7 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +exe app : app.cpp /webcpp/crypto//crypto : WEBCPP_CRYPTO_HAS_OPENSSL=1 ; diff --git a/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..6c80fb35 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/app.cpp @@ -0,0 +1,9 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include + +int main() {} diff --git a/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome new file mode 100644 index 00000000..600c34d3 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome @@ -0,0 +1,10 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: emscripten +build: fails +webcpp::crypto: OpenSSL is not built for Emscripten. In the program's Jamfile, replace /webcpp/crypto//openssl with /third_party//bearssl. diff --git a/tools/test/fixtures/crypto_jamfiles/hello/Jamfile b/tools/test/fixtures/crypto_jamfiles/hello/Jamfile new file mode 100644 index 00000000..ad3d487c --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/hello/Jamfile @@ -0,0 +1,7 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +exe hello : hello.cpp ; diff --git a/tools/test/fixtures/crypto_jamfiles/hello/hello.cpp b/tools/test/fixtures/crypto_jamfiles/hello/hello.cpp new file mode 100644 index 00000000..49ede000 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/hello/hello.cpp @@ -0,0 +1,11 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include + +int main() { + std::cout << "hello from a user's Jamfile\n"; +} diff --git a/tools/test/fixtures/crypto_jamfiles/hello/hello.outcome b/tools/test/fixtures/crypto_jamfiles/hello/hello.outcome new file mode 100644 index 00000000..6be8be2d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/hello/hello.outcome @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 +build: succeeds +run: hello +hello from a user's Jamfile From 7df9ea61539f4a72542ca37900ac2cd366491a7d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:52:11 -0300 Subject: [PATCH 06/59] tools: crypto's OpenSSL fixtures; CODING-GUIDELINES.md: crypto names the source-built OpenSSL --- CODING-GUIDELINES.md | 43 ++++++++----------- .../crypto_jamfiles/openssl_linked/Jamfile | 7 +++ .../crypto_jamfiles/openssl_linked/app.cpp | 19 ++++++++ .../openssl_linked/openssl_linked.outcome | 5 +++ .../openssl_on_emscripten/Jamfile | 7 +++ .../openssl_on_emscripten/app.cpp | 19 ++++++++ .../openssl_on_emscripten.outcome | 4 ++ 7 files changed, 79 insertions(+), 25 deletions(-) create mode 100644 tools/test/fixtures/crypto_jamfiles/openssl_linked/Jamfile create mode 100644 tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp create mode 100644 tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome create mode 100644 tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/Jamfile create mode 100644 tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/app.cpp create mode 100644 tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 7bee2900..c6620ec0 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -908,7 +908,7 @@ update --init third_party/libs/`; a build that needs none never looks. | --- | --- | --- | | `ca_certificates` | Dated Mozilla/curl CA data snapshot under `third_party/ca_certificates`, verified against its manifest and embedded by a build-generated header; updated explicitly by `tools/ca_certificates/update.py` | MPL-2.0 | | `libdatachannel` | libdatachannel 0.24.6 at `6b1e2e620f1e37f0eafeee702eaea0043cb305fd`, with pinned libjuice, libsrtp, plog and usrsctp sources; static native archives built by upstream CMake through B2 against the same source-built OpenSSL | MPL-2.0 and the nested dependencies' own licences | -| `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC and WASIp3 | Apache-2.0 | +| `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC, WASIp2 single and WASIp3 single/cooperative | Apache-2.0 | | `json-schema-test-suite` | the JSON Schema Test Suite at `5b0ee16` (2026-09-21), test data: a test that names it reads the suite at run time from the directory its define `WEBCPP_TEST_JSON_SCHEMA_TEST_SUITE` gives, on every target (wasmtime is given it, `webcpp.data`), and runs again when a file of the suite changes | MIT | | `nativejson-benchmark` | Milo Yip's nativejson-benchmark at `478d572` (2022-10-28), test data: document's benchmarks (`libs/document/bench`) read its `data/canada.json`, `data/citm_catalog.json` and `data/twitter.json` at run time under the directory its define `WEBCPP_TEST_NATIVEJSON_BENCHMARK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of them changes; its own submodules are never checked out | MIT | @@ -7196,8 +7196,9 @@ C17, and `brew install botan`) and G4 (every push). **Provider amendment, 2026-11-03.** The owner's explicit source-build request supersedes this accepted design's old OpenSSL provisioning and default-link choices (D15 and reference sections 3.3/4.4). Future crypto uses the shared -pinned `/webcpp/third_party//openssl` provider, whose current support is native -and WASIp3, static, with chapter 5 rule 7's exact-archive boundary. Statements +pinned `/webcpp/third_party//openssl` provider, whose current support is native, +WASIp2 single and WASIp3, which crypto names through its own alias +`/webcpp/crypto//openssl`, static, with chapter 5 rule 7's exact-archive boundary. Statements below about finding a machine OpenSSL, refusing all WebAssembly or defaulting to shared linkage record the older design, not current provider requirements. Botan's provisioning, future algorithms, APIs and explicit allocator policy @@ -7498,12 +7499,13 @@ are unchanged. No crypto implementation or new backend coverage is claimed. (`br_gcm_context::bctx`). Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` section 3.2 (proposals). -- **OpenSSL is the machine's libcrypto, 3.0 or later, found and never built, - native only, and its header stops with an `#error` on an older version.** - Version 3 is needed for `EVP_CIPHER_fetch`, and no OpenSSL for WASI or - Emscripten exists in webcpp's tree. - Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` - section 3.3 (proposals). +- **OpenSSL is the superproject's source-built OpenSSL 3.5.9, static, named + through `/webcpp/crypto//openssl`, which gives `WEBCPP_CRYPTO_HAS_OPENSSL` on + native, wasip2 and wasip3 and refuses Emscripten by a forced `#error`; the + backend's header stops with an `#error` when it is not linked or older than + 3.0.** Version 3 is needed for `EVP_CIPHER_fetch`; the alias follows asio's, + and OpenSSL has no canary (chapter 5 rule 7). + Source: `libs/crypto/build.jam`, `tools/webcpp-openssl.jam` (superproject). - **OpenSSL is given the key once, in `make`, webcpp keeps no copy of it, each message re-initialises the same context with a null key, and lengths are fed in pieces of at most `INT_MAX` rounded down to a multiple of 16.** A null @@ -7785,31 +7787,22 @@ are unchanged. No crypto implementation or new backend coverage is claimed. ODR violation into LNK2038. Source: `libraries/crypto/openspec/changes/genesis/design.md` D14 (proposals). -- **OpenSSL and Botan are found by `webcpp.external` (`-s_ROOT`, then +- **Botan is found by `webcpp.external` (`-s_ROOT`, then `.local/`, then the system), declared in `libs/crypto/build.jam`; a user's program that names a missing one stops the build with three ways out, - a WebAssembly build that names one stops before compiling, and only webcpp's - own tests and examples, marked by the incidental feature `webcpp-own`, are - left out.** A program that names `/third_party//openssl` has asked for it + and a WebAssembly build that names one stops before compiling (later work, + increment 5).** A program that names a backend has asked for it (the owner's decision of 2026-10-11); the index's "left out" reads every library's `build.jam`, while `third_party/Jamfile` loads only when a target names it. Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` section 4.4 (proposals). -- **OpenSSL's link, shared or static, is the propagated feature - `webcpp-crypto-openssl-link`, shared by default (`webcpp-crypto-botan-link` - for Botan), and libssl and libcrypto follow it as one target.** A header - cannot change how a program is linked, so the feature carries the owner's - choice, which the owner confirmed on 2026-10-11; one target keeps a process from - holding two copies of libcrypto. - Source: `libraries/crypto/openspec/changes/genesis/design.md` D15 - (proposals). - **One copy per program: webcpp's build of a C library is never linked with another copy of it, trystero leaves its external libsecp256k1 in the change - that names `/third_party//secp256k1`, and asio's OpenSSL moves onto - `/third_party//openssl`.** libsecp256k1's tables are global symbols; a - process with two copies of libcrypto has two memory hooks, and the install - sets only the one webcpp's backend calls. + that names `/third_party//secp256k1`, and asio and crypto name the one + source-built OpenSSL.** libsecp256k1's tables are global symbols; two + copies of libcrypto would be two error queues and two allocation hooks in + one process. Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` sections 3.5, 3.7 and 4.5 (proposals). - **Every error case of the build has a directory of its own.** b2 shares one diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_linked/Jamfile b/tools/test/fixtures/crypto_jamfiles/openssl_linked/Jamfile new file mode 100644 index 00000000..75e98760 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_linked/Jamfile @@ -0,0 +1,7 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp b/tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp new file mode 100644 index 00000000..1ed000df --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A user's program over /webcpp/crypto//openssl. Until Task 12 writes the backend's header it +// prints the define and calls OpenSSL_version_num() alone; Task 12 Step 3 gives it the seal. + +#include + +#include + +int main() { +#if defined(WEBCPP_CRYPTO_HAS_OPENSSL) + std::cout << "HAS_OPENSSL=" << WEBCPP_CRYPTO_HAS_OPENSSL << '\n'; +#endif + return OpenSSL_version_num() >= 0x30000000UL ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome b/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome new file mode 100644 index 00000000..abcdac3f --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome @@ -0,0 +1,5 @@ +[all] +targets: native wasip2 wasip3 +build: succeeds +run: app +HAS_OPENSSL=1 diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..75e98760 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/Jamfile @@ -0,0 +1,7 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..1ed000df --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/app.cpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A user's program over /webcpp/crypto//openssl. Until Task 12 writes the backend's header it +// prints the define and calls OpenSSL_version_num() alone; Task 12 Step 3 gives it the seal. + +#include + +#include + +int main() { +#if defined(WEBCPP_CRYPTO_HAS_OPENSSL) + std::cout << "HAS_OPENSSL=" << WEBCPP_CRYPTO_HAS_OPENSSL << '\n'; +#endif + return OpenSSL_version_num() >= 0x30000000UL ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome new file mode 100644 index 00000000..0c78b1e2 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome @@ -0,0 +1,4 @@ +[all] +targets: emscripten +build: fails +webcpp::crypto: /webcpp/crypto//openssl is named in a build for Emscripten, where webcpp does not build OpenSSL. From 836e89aac85a4186e9e70ae50a5184ae29daf688 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:55:26 -0300 Subject: [PATCH 07/59] tools: crypto_jamfiles tests reject a run that builds nothing, a malformed outcome and a partial line --- CODING-GUIDELINES.md | 9 +- tools/test/crypto_jamfiles_format_test.py | 113 ++++++++++++++ tools/test/crypto_jamfiles_test.py | 144 ++++++++++++++---- .../crypto_jamfiles/broken/broken.outcome | 2 +- 4 files changed, 232 insertions(+), 36 deletions(-) create mode 100644 tools/test/crypto_jamfiles_format_test.py diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 4e353bdd..28a286d3 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -101,6 +101,7 @@ Not built yet: `tools/test/oracle_jam_test.py`, `tools/test/generated_jam_test.py`, `tools/test/component_jam_test.py`, `tools/generated/generated_test.py`, `tools/test/emscripten_test.py`, `tools/test/crypto_jamfiles_test.py`, + `tools/test/crypto_jamfiles_format_test.py`, `tools/test/external_test.py`, `tools/test/doc_test.py`, `tools/test/harness_test.py`, `tools/test/third_party_test.py`, @@ -587,9 +588,11 @@ aliases, concepts, variables, data members and macros. `[emscripten]` applies by the target and the system (`[all]` and each block that matches apply). `targets: ...` (native only without it) names the targets the case is built for; `build: succeeds` or `build: fails` is - b2's exit status; after `build: fails` every other line must appear whole in - b2's output, in any order; `run: `, after `build: succeeds`, runs - the program as its lane runs one and every other line is its standard + b2's exit status; after `build: fails` every other line must be a whole line + of b2's output (trailing spaces aside), in any order; a line of one + lowercase word and a colon is reserved for these directives; + `run: `, after `build: succeeds`, runs the program as its lane runs + one and every other line is its standard output, exactly; `arguments: ...` gives b2 words for this case alone (`@scratch` is the case's scratch directory). The fixtures sit outside `libs/*/test/`, so the raw-rules lint does not apply to them. The tools job diff --git a/tools/test/crypto_jamfiles_format_test.py b/tools/test/crypto_jamfiles_format_test.py new file mode 100644 index 00000000..8b21b6d2 --- /dev/null +++ b/tools/test/crypto_jamfiles_format_test.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Checks crypto_jamfiles_test.py's own rules, without building anything: what an outcome file +may say, what a run that builds nothing is, and how a failure's lines are matched (whole lines). +""" + +from __future__ import annotations + +import subprocess +import sys +import tempfile +from pathlib import Path + +import crypto_jamfiles_test as jamfiles +import harness + +TEST = Path(__file__).resolve().parent / 'crypto_jamfiles_test.py' + + +def parse(text: str, target: str = 'native') -> jamfiles.Outcome: + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'case.outcome' + path.write_text(text) + return jamfiles.outcome(path, target) + + +def refused(text: str, *words: str) -> None: + try: + parse(text) + except jamfiles.OutcomeError as error: + assert all(word in str(error) for word in words), (text, str(error)) + return + raise AssertionError(f'accepted: {text!r}') + + +def test_a_good_outcome_is_read(): + result = parse('[all]\ntargets: native wasip2\nbuild: succeeds\nrun: app\nok\n' + '[wasip3]\nwasip3 only\n') + assert (result.targets, result.succeeds, result.run, result.lines) == ( + ['native', 'wasip2'], True, 'app', ['ok']), result + assert parse('[all]\nbuild: succeeds\nrun: app\nok\n[native]\nnative\n').lines == [ + 'ok', 'native'] + + +def test_the_format_is_enforced(): + refused('[everything]\nbuild: fails\nx\n', 'no block') + refused('build: fails\nx\n', 'before the first') + refused('[all]\nbuild: succeed\n', 'succeeds or fails') + refused('[all]\nbuild: fails\nx\nrun: app\n', 'run: after build: fails') + refused('[all]\nbuild: succeeds\nx\n', 'no run:') + refused('[all]\nbuild: fails\n', 'no line to find') + refused('[all]\nrun: app\nx\n', 'no build:') + refused('[all]\ntargets: native vax\nbuild: fails\nx\n', 'no target') + refused('[all]\nbuild: fails\nx\nargument: y\n', 'no directive') + refused('[wasip3]\nbuilds: fails\n[all]\nbuild: fails\nx\n', 'no directive') + + +def test_every_case_directory_is_read(): + cases = jamfiles.case_directories() + assert {c.name for c in cases} >= {'hello', 'broken'}, cases + + +def run(*arguments: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(TEST), *arguments], capture_output=True, + text=True, check=False) + + +def test_a_run_that_builds_nothing_fails(): + unknown = run('nonexistent_case') + assert unknown.returncode != 0 and 'no case named' in unknown.stderr, unknown + nothing = run('--target', 'wasip3', 'hello') + assert nothing.returncode != 0 and 'nothing was tested' in nothing.stderr, nothing + assert run('--target').returncode == 2 + assert run('--target', 'vax').returncode == 2 + + +def test_a_failure_line_is_matched_whole(): + printed = ['user/c/c.cpp:7:2: error: "boom"', ' 7 | #error "boom" '] + original = harness.run_b2 + + def fake(*_args, **_kwargs): + return subprocess.CompletedProcess([], 1, '\n'.join(printed) + '\n') + + harness.run_b2 = fake + try: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + case = root / 'c' + case.mkdir() + for line, faults in ((' 7 | #error "boom"', 0), ('"boom"', 1), + ('7:2: error: "boom"', 1)): + (case / 'c.outcome').write_text(f'[all]\nbuild: fails\n{line}\n') + assert len(jamfiles.run_target(root, 'native', [case])) == faults, line + finally: + harness.run_b2 = original + + +def main() -> int: + for name, case in sorted(globals().items()): + if name.startswith('test_'): + case() + print(f'{name}: ok') + print('crypto_jamfiles_format_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/test/crypto_jamfiles_test.py b/tools/test/crypto_jamfiles_test.py index 3ff1c2d8..2f9e5b11 100644 --- a/tools/test/crypto_jamfiles_test.py +++ b/tools/test/crypto_jamfiles_test.py @@ -16,6 +16,7 @@ from __future__ import annotations import platform +import re import shutil import subprocess import sys @@ -30,13 +31,21 @@ 'emscripten': ['toolset=emscripten']} SYSTEM = {'Linux': 'linux', 'Darwin': 'darwin', 'Windows': 'windows'}[platform.system()] -# Cases whose outcome needs code that is not merged yet; a run without names leaves them out, -# a run that names one builds it. Each entry names what it waits for. +# Cases whose outcome needs code that is not merged yet: a run without names leaves them out +# (and says so), a run that names one builds it. Each entry names what it waits for. The +# integrator empties it when the code it waits for is merged. NOT_YET = { 'has_openssl_on_emscripten': 'the refusal in config.hpp (Task 6)', 'default_openssl_on_emscripten': 'the refusal in config.hpp (Task 6)', } +BLOCKS = {'all', 'native', 'native-linux', 'native-darwin', 'native-windows', 'wasip2', 'wasip3', + 'emscripten'} + + +class OutcomeError(Exception): + """An outcome file or a case directory that does not follow the format.""" + def launcher(target: str) -> Path: """The script the lanes run a WASI program with (tools/ci/matrix.py, wasm_lane).""" @@ -47,28 +56,48 @@ def launcher(target: str) -> Path: class Outcome: """What an outcome file says for one target.""" targets: list[str] = field(default_factory=lambda: ['native']) - succeeds: bool = True + succeeds: bool | None = None run: str | None = None lines: list[str] = field(default_factory=list) arguments: list[str] = field(default_factory=list) def outcome(path: Path, target: str) -> Outcome: - """The blocks of path that apply to target on this system, read into an Outcome.""" + """The blocks of path that apply to target on this system, read into an Outcome. Every line + of the file is checked, whether its block applies or not, and so is the outcome that results + when target is one the case is built for (checked).""" applying = {'all', target} | ({'native', 'native-' + SYSTEM} if target == 'native' else set()) result = Outcome() block = None - for raw in path.read_text().splitlines(): + for number, raw in enumerate(path.read_text().splitlines(), 1): + where = f'{path.name}:{number}' if not raw.strip() or raw.startswith('#'): continue if raw.startswith('[') and raw.endswith(']'): block = raw[1:-1] + if block not in BLOCKS: + raise OutcomeError(f'{where}: no block [{block}]; the blocks are {sorted(BLOCKS)}') continue if block is None: - raise SystemExit(f'{path}: a line before the first [block]: {raw!r}') + raise OutcomeError(f'{where}: a line before the first [block]: {raw!r}') + directive = re.match(r'([a-z]+):(?: |$)', raw) + key, value = (directive.group(1), raw[directive.end():]) if directive else ('', raw) + if key and key not in ('targets', 'build', 'run', 'arguments'): + raise OutcomeError(f'{where}: no directive {key}: (a line of one lowercase word and ' + f'a colon is reserved for them): {raw!r}') + if key in ('targets', 'arguments') and not value.split(): + raise OutcomeError(f'{where}: {key}: names nothing') + if key == 'targets': + unknown = [t for t in value.split() if t not in TOOLSETS] + if unknown: + raise OutcomeError( + f'{where}: no target {unknown}; the targets are {list(TOOLSETS)}') + elif key == 'build' and value not in ('succeeds', 'fails'): + raise OutcomeError(f'{where}: build: is succeeds or fails, not {value!r}') + elif key == 'run' and not value: + raise OutcomeError(f'{where}: run: names no program') if block not in applying: continue - key, _, value = raw.partition(': ') if key == 'targets': result.targets = value.split() elif key == 'build': @@ -79,16 +108,49 @@ def outcome(path: Path, target: str) -> Outcome: result.arguments += value.split() else: result.lines.append(raw) + if target in result.targets: + checked(path, target, result) return result +def checked(path: Path, target: str, result: Outcome) -> None: + """Raises an OutcomeError naming path and target unless result is coherent: a build is said + to succeed or fail; a failure has lines to find and no program to run; a success that + prints lines has a program.""" + if result.succeeds is None: + raise OutcomeError(f'{path.name} on {target}: no build: line') + if not result.succeeds and result.run is not None: + raise OutcomeError(f'{path.name} on {target}: run: after build: fails') + if not result.succeeds and not result.lines: + raise OutcomeError(f'{path.name} on {target}: build: fails with no line to find') + if result.succeeds and result.run is None and result.lines: + raise OutcomeError(f'{path.name} on {target}: lines after build: succeeds, with no run:') + + +def case_directories() -> list[Path]: + """Every directory of CASES, each with its one outcome file named after it, and every + outcome file read for every target (so each line of each block is checked), else an + OutcomeError.""" + cases = sorted(p for p in CASES.iterdir() if p.is_dir()) + for case in cases: + found = sorted(p.name for p in case.glob('*.outcome')) + if found != [case.name + '.outcome']: + raise OutcomeError(f'{case.name}: the outcome files are {found}; ' + f'the one is {case.name}.outcome') + if not (case / 'Jamfile').is_file(): + raise OutcomeError(f'{case.name}: no Jamfile') + for target in TOOLSETS: + outcome(case / f'{case.name}.outcome', target) + return cases + + def program_command(build_dir: Path, case: str, name: str, target: str) -> list[str]: """The command that runs the program name that the build of case made under build_dir, as its lane runs one.""" suffix = {'native': '.exe' if SYSTEM == 'windows' else '', 'wasip2': '.wasm', 'wasip3': '.wasm', 'emscripten': '.js'}[target] found = [p for p in build_dir.rglob(name + suffix) - if p.is_file() and f'user/{case}/' in p.relative_to(build_dir).as_posix() + '/'] + if p.is_file() and f'user/{case}/' in p.relative_to(build_dir).as_posix()] if len(found) != 1: raise AssertionError(f'the build made {len(found)} files named {name}{suffix}') if target == 'emscripten': @@ -98,16 +160,12 @@ def program_command(build_dir: Path, case: str, name: str, target: str) -> list[ return [str(found[0])] -def selected(names: list[str], target: str) -> list[Path]: - """The case directories to build for target: the named ones, else every one that is not in - NOT_YET, each that its outcome file's targets line names target for.""" - cases = [] - for case in sorted(p.parent for p in CASES.glob('*/*.outcome')): - if (names and case.name not in names) or (not names and case.name in NOT_YET): - continue - if target in outcome(next(case.glob('*.outcome')), target).targets: - cases.append(case) - return cases +def selected(cases: list[Path], names: list[str], target: str) -> list[Path]: + """The cases to build for target: the named ones, else every one that is not in NOT_YET, + each that its outcome file's targets line names target for.""" + return [case for case in cases + if (case.name in names if names else case.name not in NOT_YET) + and target in outcome(case / f'{case.name}.outcome', target).targets] def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: @@ -115,12 +173,12 @@ def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: faults: list[str] = [] build_dir = root / 'bin' / f'user-{target}' for case in cases: - expected = outcome(next(case.glob('*.outcome')), target) + expected = outcome(case / f'{case.name}.outcome', target) scratch = root / 'scratch' / case.name scratch.mkdir(parents=True, exist_ok=True) arguments = [a.replace('@scratch', str(scratch)) for a in expected.arguments] - launch = [f'testing.launcher={launcher(target)}'] if target.startswith('wasi') else [] - built = harness.run_b2(root, f'--build-dir={build_dir}', *TOOLSETS[target], *launch, + # No testing.launcher: a user's exe is run by this test, not by b2. + built = harness.run_b2(root, '-j3', f'--build-dir={build_dir}', *TOOLSETS[target], *arguments, f'user/{case.name}') output = built.stdout if (built.returncode == 0) != expected.succeeds: @@ -128,11 +186,16 @@ def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: f'{"succeeded" if built.returncode == 0 else "failed"}\n{output[-3000:]}') continue if not expected.succeeds: - faults += [f'{case.name} on {target}: b2 did not print: {line}' - for line in expected.lines if line not in output] + printed = {line.rstrip() for line in output.splitlines()} + faults += [f'{case.name} on {target}: b2 printed no line {line!r}' + for line in expected.lines if line.rstrip() not in printed] continue if expected.run is not None: - command = program_command(build_dir, case.name, expected.run, target) + try: + command = program_command(build_dir, case.name, expected.run, target) + except AssertionError as error: + faults.append(f'{case.name} on {target}: {error}') + continue ran = subprocess.run(command, capture_output=True, text=True, check=False) printed = ran.stdout.replace('\r\n', '\n').splitlines() if ran.returncode != 0 or printed != expected.lines: @@ -144,17 +207,32 @@ def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: def main(argv: list[str]) -> int: targets = list(TOOLSETS) if '--target' in argv: - targets = [argv[argv.index('--target') + 1]] - argv = [a for a in argv if a not in ('--target', targets[0])] - if targets[0] not in TOOLSETS: - raise SystemExit(f'crypto_jamfiles: no target {targets[0]}; ' - f'the targets are {list(TOOLSETS)}') + position = argv.index('--target') + if position + 1 >= len(argv) or argv[position + 1] not in TOOLSETS: + print(f'crypto_jamfiles: --target takes one of {list(TOOLSETS)}', file=sys.stderr) + return 2 + targets = [argv[position + 1]] + argv = argv[:position] + argv[position + 2:] names = [a for a in argv if not a.startswith('--')] + try: + cases = case_directories() + except OutcomeError as error: + print(f'crypto_jamfiles: {error}', file=sys.stderr) + return 2 + missing = [n for n in names if n not in {c.name for c in cases}] + if missing: + print(f'crypto_jamfiles: no case named {missing}', file=sys.stderr) + return 2 + if not names and NOT_YET: + for case, reason in NOT_YET.items(): + print(f'left out until {reason}: {case}') faults: list[str] = [] + built = 0 for target in targets: - cases = selected(names, target) - if not cases: + chosen = selected(cases, names, target) + if not chosen: continue + built += len(chosen) started = time.monotonic() root = harness.scratch_superproject() try: @@ -164,10 +242,12 @@ def main(argv: list[str]) -> int: harness.link_emsdk(root) elif target.startswith('wasi'): harness.link_wasi_tools(root) - faults += run_target(root, target, cases) + faults += run_target(root, target, chosen) finally: shutil.rmtree(root) print(f'{target}: done in {time.monotonic() - started:.0f} s') + if not built: + faults.append(f'no case was built for {targets}; nothing was tested') for fault in faults: print(f'crypto_jamfiles: {fault}', file=sys.stderr) print('crypto_jamfiles_test: ' + ('failed' if faults else 'ok')) diff --git a/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome b/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome index f9a0111f..cac4e663 100644 --- a/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome +++ b/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome @@ -6,4 +6,4 @@ [all] build: fails -broken on purpose + 7 | #error "broken on purpose" From efff69f6fc881d4d31d40abbc58e151d124e402d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:55:34 -0300 Subject: [PATCH 08/59] tools: openssl_one_copy_test.py asserts the single OpenSSL copy; CODING-GUIDELINES.md: OpenSSL targets and alias name --- CODING-GUIDELINES.md | 24 ++++----- tools/test/openssl_one_copy_test.py | 76 +++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 11 deletions(-) create mode 100644 tools/test/openssl_one_copy_test.py diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index c6620ec0..f0e46621 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -6725,7 +6725,8 @@ supersedes the temporary system-OpenSSL choice; it does not reopen every rule. - Plain `/webcpp/cobalt//core` omits SSL; the explicit `/webcpp/cobalt//io_ssl` supplies the corrected native or WASI wrapper. - The former shared system OpenSSL/native-only bridge is superseded by the - pinned static source provider on native and WASIp3, without waiting for crypto. + pinned static source provider on native, WASIp2 single and WASIp3, without + waiting for crypto. Chapter 5 rule 7 retains its Configure/Make and exact-archive canary exception. - Dedicated no-exceptions programs and local complete suites run natively; the general CI-level expansion remains chapter 16 work. Do not mistake those @@ -7196,9 +7197,10 @@ C17, and `brew install botan`) and G4 (every push). **Provider amendment, 2026-11-03.** The owner's explicit source-build request supersedes this accepted design's old OpenSSL provisioning and default-link choices (D15 and reference sections 3.3/4.4). Future crypto uses the shared -pinned `/webcpp/third_party//openssl` provider, whose current support is native, -WASIp2 single and WASIp3, which crypto names through its own alias -`/webcpp/crypto//openssl`, static, with chapter 5 rule 7's exact-archive boundary. Statements +pinned `/webcpp/third_party//openssl` provider, whose current support is +native, WASIp2 single and WASIp3, static, with chapter 5 rule 7's exact-archive +boundary, and which crypto names through its own alias +`/webcpp/crypto//openssl`. Statements below about finding a machine OpenSSL, refusing all WebAssembly or defaulting to shared linkage record the older design, not current provider requirements. Botan's provisioning, future algorithms, APIs and explicit allocator policy @@ -7581,7 +7583,7 @@ are unchanged. No crypto implementation or new backend coverage is claimed. (proposals). - **The backends' page and `gcm`'s page warn that natively without OpenSSL BearSSL is 30 to 62 times slower than OpenSSL on ARM, and that a server on - ARM names `/third_party//openssl`.** BearSSL has no ARMv8 AES or PMULL code. + ARM names `/webcpp/crypto//openssl`.** BearSSL has no ARMv8 AES or PMULL code. Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` section 5 (proposals). @@ -7661,8 +7663,8 @@ are unchanged. No crypto implementation or new backend coverage is claimed. - **`WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, native only, sends every allocation of OpenSSL in the process to a `std::pmr::memory_resource`; the - program gives it with `/third_party//openssl` in its project's - requirements, and `config.hpp` refuses it on WebAssembly and without OpenSSL + program gives it with `/webcpp/crypto//openssl` in its project's + requirements, and `config.hpp` refuses it on Emscripten and without OpenSSL linked.** The owner's decision of 2026-10-11 made `CRYPTO_set_mem_functions` an option of the config, so that a program that wants OpenSSL's allocations in its own allocator can say so; the library beside the define keeps every @@ -7815,10 +7817,10 @@ are unchanged. No crypto implementation or new backend coverage is claimed. - **The library targets native (Linux x86-64 and arm64, macOS arm64, Windows with MSVC), wasip2, wasip3 and Emscripten, and each backend runs where its - library exists: BearSSL, ctaes and libsecp256k1 on every target, OpenSSL and - Botan natively only; a Botan WebAssembly build is a later increment's.** The - rulebook's targets; no OpenSSL or Botan for WebAssembly exists that webcpp's - build can find. + library exists: BearSSL, ctaes and libsecp256k1 on every target, OpenSSL on + native, wasip2 and wasip3, Botan natively only; a Botan WebAssembly build is + a later increment's.** The rulebook's targets; webcpp builds no OpenSSL for + Emscripten and no Botan for WebAssembly. Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` section 3.1 (proposals). - **On Windows `/webcpp/crypto//crypto` adds `bcrypt` to its usage diff --git a/tools/test/openssl_one_copy_test.py b/tools/test/openssl_one_copy_test.py new file mode 100644 index 00000000..0779fd75 --- /dev/null +++ b/tools/test/openssl_one_copy_test.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) +"""Checks that asio's and crypto's OpenSSL aliases in one program link libssl.a and libcrypto.a +once each, from one directory (CODING-GUIDELINES.md chapter 5 rule 10). + +It reads the link line b2 prints (-d+2 with -n, so nothing is rebuilt) for +libs/crypto/test//openssl_one_copy and its _no_exceptions twin, and fails on any archive count +other than one per program, or on archives from two directories. +""" +import os +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ARCHIVE = re.compile(r'[^\s"]*/lib(ssl|crypto)\.a') +LINK = re.compile(r'-o "?[^\s"]*/openssl_one_copy(_no_exceptions)?"?(\s|$)') + + +def check_link_line(line: str) -> list[str]: + """The faults of one link line: an archive not exactly once, or two directories.""" + found = [m.group(0) for m in ARCHIVE.finditer(line)] + faults = [] + for name in ('libssl.a', 'libcrypto.a'): + count = sum(1 for path in found if path.endswith('/' + name)) + if count != 1: + faults.append(f'{name} is linked {count} times') + if len({path.rsplit('/', 1)[0] for path in found}) > 1: + faults.append(f'the archives come from different directories: {sorted(set(found))}') + return faults + + +def self_test() -> None: + """The checker itself: a line with a repeated archive or two directories must fail.""" + good = '-o "x/openssl_one_copy" /a/config-1/libssl.a /a/config-1/libcrypto.a' + assert check_link_line(good) == [] + twice = good + ' /a/config-1/libssl.a' + assert check_link_line(twice) == ['libssl.a is linked 2 times'] + split = '-o "x/openssl_one_copy" /a/config-1/libssl.a /b/config-2/libcrypto.a' + assert 'different directories' in ' '.join(check_link_line(split)) + assert check_link_line('-o "x/openssl_one_copy"') != [] + + +def main() -> int: + self_test() + env = {k: v for k, v in os.environ.items() if k not in ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH')} + command = ['b2', f'--user-config={ROOT}/.local/user-config.jam', '-a', '-n', '-d+2', '-j3', + '--build-dir=' + str(ROOT / 'bin/lane-onecopy'), *sys.argv[1:], + 'libs/crypto/test//openssl_one_copy', 'libs/crypto/test//openssl_one_copy_no_exceptions'] + result = subprocess.run(command, cwd=ROOT, env=env, capture_output=True, text=True, check=False) + if result.returncode != 0: + print(result.stdout + result.stderr, file=sys.stderr) + return 1 + lines = [line for line in result.stdout.splitlines() if LINK.search(line) and ARCHIVE.search(line)] + # b2 prints a command on several lines; join each link command from its -o line to the next blank. + text = result.stdout + commands = [chunk for chunk in re.split(r'\n\s*\n', text) if LINK.search(chunk) and ARCHIVE.search(chunk)] + if len(commands) != 2: + print(f'openssl_one_copy: expected 2 link commands, found {len(commands)} ({len(lines)} lines)', + file=sys.stderr) + return 1 + faults = [fault for chunk in commands for fault in check_link_line(chunk)] + for fault in faults: + print(f'openssl_one_copy: {fault}', file=sys.stderr) + if not faults: + print('openssl_one_copy_test: ok') + return 1 if faults else 0 + + +if __name__ == '__main__': + sys.exit(main()) From e4f3d9165294c873d2e33f78b18692c835612db6 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:30:23 -0300 Subject: [PATCH 09/59] third_party: Wycheproof, pinned and shallow --- .gitmodules | 4 ++++ CODING-GUIDELINES.md | 1 + doc/releases/0.1.0.adoc | 2 ++ third_party/Jamfile | 24 ++++++++++++++++++++++++ third_party/libs/wycheproof | 1 + tools/test/third_party_test.py | 12 ++++++++++++ 6 files changed, 44 insertions(+) create mode 160000 third_party/libs/wycheproof diff --git a/.gitmodules b/.gitmodules index 3762d051..0154f875 100644 --- a/.gitmodules +++ b/.gitmodules @@ -49,3 +49,7 @@ [submodule "libs/cobalt"] path = libs/cobalt url = ../cobalt.git +[submodule "third_party/libs/wycheproof"] + path = third_party/libs/wycheproof + url = https://github.com/C2SP/wycheproof.git + shallow = true diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 7bee2900..c3352391 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -911,6 +911,7 @@ update --init third_party/libs/`; a build that needs none never looks. | `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC and WASIp3 | Apache-2.0 | | `json-schema-test-suite` | the JSON Schema Test Suite at `5b0ee16` (2026-09-21), test data: a test that names it reads the suite at run time from the directory its define `WEBCPP_TEST_JSON_SCHEMA_TEST_SUITE` gives, on every target (wasmtime is given it, `webcpp.data`), and runs again when a file of the suite changes | MIT | | `nativejson-benchmark` | Milo Yip's nativejson-benchmark at `478d572` (2022-10-28), test data: document's benchmarks (`libs/document/bench`) read its `data/canada.json`, `data/citm_catalog.json` and `data/twitter.json` at run time under the directory its define `WEBCPP_TEST_NATIVEJSON_BENCHMARK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of them changes; its own submodules are never checked out | MIT | +| `wycheproof` | C2SP's Wycheproof at `12fd3aaf` (2026-10-06), shallow, test data: crypto's tests read its `testvectors_v1/` at run time under the directory its define `WEBCPP_TEST_WYCHEPROOF` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of its files changes | Apache-2.0 | OpenSSL builds from a checkout or a source distribution. Before Configure, its builder stages the distributable tree and checks a digest of paths, Git file diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 8247746f..c5b68d07 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -120,6 +120,8 @@ announce and package a release. * Added `third_party/`, third-party code pinned as submodules: first the JSON Schema Test Suite, which a test reads on every target through `/webcpp/third_party//json-schema-test-suite`. +* Added Wycheproof's test vectors to `third_party/`, which a test reads on every +target through `/webcpp/third_party//wycheproof`. * Changed the lint to never read third-party code under `third_party/libs/`. * Added `webcpp.generated`, which checks a library's generated files against their Python generator, and `update-generated`, their only writer. diff --git a/third_party/Jamfile b/third_party/Jamfile index c1895c4a..ffb8ed2c 100644 --- a/third_party/Jamfile +++ b/third_party/Jamfile @@ -79,6 +79,30 @@ alias nativejson-benchmark : : @nativejson-checked-out : : explicit nativejson-benchmark ; +# Wycheproof (Apache-2.0), C2SP/wycheproof: test data, never compiled. A test +# that names wycheproof reads it from the directory WEBCPP_TEST_WYCHEPROOF +# names, with forward slashes, the directory given to wasmtime on WASI +# (webcpp.data), and runs again when one of its files changes. +path-constant WYCHEPROOF : libs/wycheproof ; +.wycheproof = [ regex.replace $(WYCHEPROOF) "\\\\" "/" ] ; +.wycheproof-files = [ glob libs/wycheproof/testvectors_v1/*.json ] ; + +rule wycheproof-checked-out ( properties * ) +{ + if ! [ path.exists [ path.native $(WYCHEPROOF)/testvectors_v1/aes_gcm_test.json ] ] + { + errors.user-error "third_party/libs/wycheproof is not checked out: it holds no" + "testvectors_v1/aes_gcm_test.json. Check it out with `git submodule update" + "--init third_party/libs/wycheproof`." ; + } +} + +alias wycheproof : : @wycheproof-checked-out : : + "\"WEBCPP_TEST_WYCHEPROOF=\\\"$(.wycheproof)\\\"\"" + [ webcpp.data $(WYCHEPROOF) ] + $(.wycheproof-files) ; +explicit wycheproof ; + # OpenSSL uses its upstream Configure/Make source manifest. The bridge emits # static archives and matching generated headers in B2's variant directory. import webcpp-openssl ; diff --git a/third_party/libs/wycheproof b/third_party/libs/wycheproof new file mode 160000 index 00000000..12fd3aaf --- /dev/null +++ b/third_party/libs/wycheproof @@ -0,0 +1 @@ +Subproject commit 12fd3aaf33eb5fa1f52e026912ee00c054f9d984 diff --git a/tools/test/third_party_test.py b/tools/test/third_party_test.py index edcc4851..4718faa2 100755 --- a/tools/test/third_party_test.py +++ b/tools/test/third_party_test.py @@ -36,6 +36,11 @@ # The commit the suite is pinned at, of 2026-09-21. SUITE_COMMIT = '5b0ee1613e45fcc2bddac00e07c19cd49b00d8a8' +WYCHEPROOF = 'third_party/libs/wycheproof' + +# The commit Wycheproof is pinned at, of 2026-10-06. +WYCHEPROOF_COMMIT = '12fd3aaf33eb5fa1f52e026912ee00c054f9d984' + READER_JAMFILE = ('import webcpp ;\n' '\n' 'webcpp.targets native wasip2 wasip3 emscripten ;\n' @@ -94,6 +99,12 @@ def test_the_suite_is_pinned(_: Path) -> None: assert listed.stdout.split()[:2] == ['160000', SUITE_COMMIT], listed.stdout +def test_wycheproof_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', WYCHEPROOF], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', WYCHEPROOF_COMMIT], listed.stdout + + def test_the_suite_reaches_a_native_test(root: Path) -> None: add_reader(root) result = harness.run_b2(root, '-a', 'libs/suite_reader/test') @@ -158,6 +169,7 @@ def test_a_suite_not_checked_out_is_refused(root: Path) -> None: CASES = [ test_the_suite_is_pinned, + test_wycheproof_is_pinned, test_the_suite_reaches_a_native_test, test_the_suite_reaches_a_test_on_emscripten, test_the_suite_reaches_a_test_on_wasi, From f194b745da070b72e2e9e7d201da19a354283f96 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:50:58 -0300 Subject: [PATCH 10/59] tools: the lint refuses a weaker source in a header that reads entropy --- CODING-GUIDELINES.md | 1 + doc/releases/0.1.0.adoc | 1 + tools/lint/lint.sh | 16 ++++++++++++++++ tools/lint/lint_test.py | 26 ++++++++++++++++++++++++++ 4 files changed, 44 insertions(+) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 7bee2900..9962ad84 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -599,6 +599,7 @@ with `lint: failed: ` for each rule that failed. | licence notice | a source file (C++, JavaScript, AsciiDoc, Python, shell, Jam, YAML, HTML) that does not open with the notice (chapter 2) | | banned word | the word that the pattern `veru[s]` matches, in any case, in a file, a file name or a commit (its author, committer or message) of any repository | | no clock, disk or network | a library header that names a clock, a file, a socket, a process, a thread, the environment or entropy (`random_device`, `getentropy`, `getrandom`, `arc4random`, OpenSSL's `RAND_bytes`, ``) without `lint-world:` | +| entropy sources | a library header whose path ends `entropy.hpp` or `random_device.hpp` that names `rand`, `srand`, `time`, `clock` or `__rdrand`, even with `lint-world:` | | raw b2 rules | `run`, `run-fail`, `compile`, `compile-fail`, `exe`, `unit-test`, `link` or `link-fail` in a library's test or example Jamfile (`AGENTS.md` chapter 4) | | Doc Comments | a command webcpp does not allow, a bare `@`, or a colon after a reference (chapter 7) | | Pyright | an error or a warning in any Python file, with `pyrightconfig.json` (unused imports and variables are errors) | diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 8247746f..feeb47a6 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -225,6 +225,7 @@ Emscripten's notice that the runtime is kept alive. `EM_JS` function or an `EM_ASM` block. * Added the project id /third_party, the form a user's Jamfile writes for third-party code. +* Added the lint rule entropy sources, which refuses a weaker source in a header that reads entropy. [#webcpp-0-1-0-compilers-tested] == Compilers tested diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index b4614a96..df02046e 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -613,6 +613,22 @@ else printf ' the entropy\n' fi +# 8a. A header that reads entropy names no weaker source: no rand, time, clock or +# __rdrand, even with lint-world:, in any header whose path ends entropy.hpp or +# random_device.hpp (DESIGN, 2026-10-11 "entropy, safest and readable"). +rule 'entropy sources' +files_matching '^(libs|tools/test/fixtures)/[^/]+/include/.*(entropy|random_device)\.hpp$' \ + > "${work_directory}/entropy_headers" +weak='(^|[^_[:alnum:]])(s?rand|time|clock|__rdrand(16|32|64)?_step|__rdrand)[[:space:]]*\(' +weak_found="$(on_files "${work_directory}/entropy_headers" grep -nHE -e "${weak}" || true)" +if [ -n "${weak_found}" ]; then + printf '%s\n' "${weak_found}" \ + | sed 's/$/: a header that reads entropy names rand, time, clock or __rdrand/' + fail "a header that reads entropy names a weaker source" +else + printf 'no header that reads entropy names a weaker source\n' +fi + # 9. A library's test and example Jamfiles declare their programs with tools/webcpp.jam's rules, # which build each only for the targets it declares and add what every program needs; b2's # own run, run-fail, compile, compile-fail, exe and unit-test do neither (tools/lint/rules.py). diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 5c2fa072..6a9c8a5c 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -1716,6 +1716,31 @@ def test_world_rule(root): 'libs/demo/test/pass.cpp')) +def test_entropy_sources(root): + prepare(root) + header = 'libs/demo/include/webcpp/demo/entropy.hpp' + # A header that reads entropy names no weaker source, even with lint-world:, which spares it + # from the rule above but not from this one. getentropy is the source, not a weaker one. + write(root, header, + '// Copyright (c) 2026 WebCpp.org\n' + '//\n' + '// Distributed under the Boost Software License, Version 1.0. (See\n' + '// accompanying file LICENSE_1_0.txt or copy at\n' + '// https://www.boost.org/LICENSE_1_0.txt)\n' + '\n' + '#ifndef WEBCPP_DEMO_ENTROPY_HPP\n' + '#define WEBCPP_DEMO_ENTROPY_HPP\n' + '\n' + '// Calls rand(). lint-world: a test\n' + '// Calls getentropy(p, 16). lint-world: a test\n' + '\n' + '#endif // WEBCPP_DEMO_ENTROPY_HPP\n') + expect_alone(lint(root), 'entropy sources', [ + at(root, header, 'rand()'), + ': a header that reads entropy names rand, time, clock or __rdrand', + ], spared=(at(root, header, 'getentropy'),)) + + def test_bare_throw(root): prepare(root) # A library header raises through boost::throw_exception alone. A throw in a template that @@ -2503,6 +2528,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_banned_word, test_third_party_code_is_never_read, test_world_rule, + test_entropy_sources, test_bare_throw, test_raw_rules, test_include_boundaries_angle_brackets, From 2aa31edc07704aa5e9b7baa39e0c7b870715068b Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:50:08 -0300 Subject: [PATCH 11/59] tools: the lint checks each canary's commit against its submodule --- CODING-GUIDELINES.md | 1 + doc/releases/0.1.0.adoc | 1 + tools/lint/lint.sh | 35 ++++++++++++++++++++++++- tools/lint/lint_test.py | 58 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 1 deletion(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index c3352391..ad876739 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -610,6 +610,7 @@ with `lint: failed: ` for each rule that failed. | include boundaries | an `#include` that crosses a boundary the library declares in its `meta/include-boundaries.json` (below), at its line, with the boundary's reason; and a malformed file, or a glob that matches no file of the library | | bare throw | a `throw` expression in a library's public header (`libs/*/include/**`), outside comments and literals, at its line: inside `#ifndef WEBCPP__NO_EXCEPTIONS` too, in a template that nothing instantiates, which clang-tidy's analysis without exceptions does not see, and as a rethrow, `throw;`; `boost::throw_exception` is the one way to raise, `std::rethrow_exception` the one way to rethrow (above) | | changelog form | a library's changelog or a version's release notes out of `AGENTS.md` chapter 5's form: a section or a region missing or out of order, a line that starts with no verb of the list, a cross-reference, more than ten lines for a library and a version, text outside a bullet | +| canary pins | a `WEBCPP_CRYPTO__COMMIT` of crypto's `detail/canary.h` that is not the first seven digits of the commit the superproject records for `third_party/libs/` | A source b2 expects not to compile (`webcpp.compile-fail`), and one that must stop with the error it states (`webcpp.compile-diagnostic`), are left diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index c5b68d07..3edf633b 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -227,6 +227,7 @@ Emscripten's notice that the runtime is kept alive. `EM_JS` function or an `EM_ASM` block. * Added the project id /third_party, the form a user's Jamfile writes for third-party code. +* Added the lint rule canary pins, which checks crypto's canaries against their submodules. [#webcpp-0-1-0-compilers-tested] == Compilers tested diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index b4614a96..702e0634 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -28,7 +28,8 @@ # or class, that a comment of a Jam file keeps to 80 columns, that a library header raises # through boost::throw_exception, never with a bare throw, that no code span of a Doc Comment # holds __X__ unescaped, which MrDocs shows as a bold X, and that a library's changelog and a -# version's release notes keep their form. +# version's release notes keep their form, and that each canary of webcpp::crypto is pinned at +# its submodule's commit. # # clang-tidy reads the compilation database of tools/lint/compile_commands.py: what b2 compiles # for the libraries' tests and examples and for their own lanes, a served component among them, @@ -768,6 +769,38 @@ else fail 'a changelog breaks its form (AGENTS.md chapter 5)' fi +# 19. Each canary's commit is its submodule's (CODING-GUIDELINES.md chapter 5, rule 11): +# every `#define WEBCPP_CRYPTO__COMMIT ` of crypto's detail/canary.h names +# the first seven digits of the commit the superproject records for +# third_party/libs/, read from git, so that no checkout is needed. The +# submodule is the canary's name, except ctaes, which Bitcoin Core's submodule holds. +rule 'canary pins' +canary_header='libs/crypto/include/webcpp/crypto/detail/canary.h' +pins="$(grep -hoE '^#define WEBCPP_CRYPTO_[A-Z0-9]+_COMMIT [0-9a-f]{7}$' \ + "${canary_header}" 2>/dev/null || true)" +pin_faults='' +while read -r _ macro hex; do + [ -n "${macro}" ] || continue + name="$(printf '%s' "${macro}" | sed -E 's/^WEBCPP_CRYPTO_(.*)_COMMIT$/\1/' | tr 'A-Z' 'a-z')" + case "${name}" in + ctaes) submodule='bitcoin' ;; + *) submodule="${name}" ;; + esac + head="$(git rev-parse --short=7 "HEAD:third_party/libs/${submodule}" 2>/dev/null || printf 'missing')" + if [ "${head}" != "${hex}" ]; then + pin_faults="${pin_faults}${canary_header}: ${name} is pinned at ${hex} and third_party/libs/${submodule} is at ${head} +" + fi +done < None: + """Records the gitlink third_party/libs/name at commit_id in the scratch superproject's index, + as a submodule's is, without a checkout; the link the scratch copy has for third_party/libs + gives way to a directory first.""" + libs = root / 'third_party/libs' + if libs.is_symlink(): + git(root, 'rm', '-q', '--cached', 'third_party/libs') + libs.unlink() + libs.mkdir() + git(root, 'update-index', '--add', '--cacheinfo', + f'160000,{commit_id},third_party/libs/{name}') + + +def commit_recorded(root: Path, message: str) -> None: + """Commits the header and the gitlinks recorded, without commit's git add -A, which would + drop a gitlink whose directory is not there.""" + git(root, 'add', CANARY_HEADER) + git(root, 'commit', '-q', '-m', message) + + +def test_canary_pins(root): + prepare(root) + # Each pin of detail/canary.h is the first seven digits of the commit the superproject + # records for its submodule, ctaes' for bitcoin's; the macro of a test's override, an + # indented line and a pin of no submodule recorded are not pins read. A pin that differs fails + # at the header, naming both. + bearssl = '7bea48e5e850ab4cafbe68d3765cdaba13a86d6f' + bitcoin = '1234567890abcdef1234567890abcdef12345678' + record_submodule(root, 'bearssl', bearssl) + record_submodule(root, 'bitcoin', bitcoin) + write(root, CANARY_HEADER, CANARY.format(bearssl='7bea48e', ctaes='1234567')) + commit_recorded(root, 'A canary') + expect_clean(lint(root)) + write(root, CANARY_HEADER, CANARY.format(bearssl='1234567', ctaes='1234568')) + commit_recorded(root, 'Canaries at other commits') + expect_alone(lint(root), 'canary pins', [ + f'{CANARY_HEADER}: bearssl is pinned at 1234567 and third_party/libs/bearssl is at 7bea48e', + f'{CANARY_HEADER}: ctaes is pinned at 1234568 and third_party/libs/bitcoin is at 1234567', + ]) + record_submodule(root, 'bearssl', '1234567' + bearssl[7:]) + write(root, CANARY_HEADER, CANARY.format(bearssl='1234567', ctaes='1234567')) + commit_recorded(root, 'Canaries at the recorded commits') + expect_clean(lint(root)) + git(root, 'rm', '-q', '--cached', 'third_party/libs/bearssl') + commit_recorded(root, 'No bearssl') + expect_alone(lint(root), 'canary pins', [ + 'bearssl is pinned at 1234567 and third_party/libs/bearssl is at missing']) + + def test_pyright(root): prepare(root) # A warning fails as an error does. lint_test.py itself proves the import paths: it imports @@ -2520,6 +2577,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_doc_comment_references, test_doc_comment_code_spans, test_changelog, + test_canary_pins, test_pyright, test_python_line_length, test_python_blank_lines, From 947092109e8c7c3d4de18f72dfee4921d5b96c4e Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:57:17 -0300 Subject: [PATCH 12/59] tools: crypto_jamfiles outcome files state any output line with line:, and refuse a leftover option --- CODING-GUIDELINES.md | 4 +++- tools/test/crypto_jamfiles_format_test.py | 13 +++++++++++++ tools/test/crypto_jamfiles_test.py | 11 ++++++++--- .../default_openssl_on_emscripten.outcome | 2 ++ .../has_openssl_on_emscripten.outcome | 2 ++ 5 files changed, 28 insertions(+), 4 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 28a286d3..74163c15 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -590,7 +590,9 @@ aliases, concepts, variables, data members and macros. the targets the case is built for; `build: succeeds` or `build: fails` is b2's exit status; after `build: fails` every other line must be a whole line of b2's output (trailing spaces aside), in any order; a line of one - lowercase word and a colon is reserved for these directives; + lowercase word and a colon is reserved for these directives, and + `line: ` states a literal output line, empty for a blank one, also for + a line that starts with `#`, `[` or such a word; `run: `, after `build: succeeds`, runs the program as its lane runs one and every other line is its standard output, exactly; `arguments: ...` gives b2 words for this case alone diff --git a/tools/test/crypto_jamfiles_format_test.py b/tools/test/crypto_jamfiles_format_test.py index 8b21b6d2..cf9ba39a 100644 --- a/tools/test/crypto_jamfiles_format_test.py +++ b/tools/test/crypto_jamfiles_format_test.py @@ -60,6 +60,19 @@ def test_the_format_is_enforced(): refused('[wasip3]\nbuilds: fails\n[all]\nbuild: fails\nx\n', 'no directive') +def test_line_states_a_literal_output_line(): + lines = parse('[all]\nbuild: fails\nline: error: x\nline:\nline: # c\nline: [x]\n' + 'line: line: y\n').lines + assert lines == ['error: x', '', '# c', '[x]', 'line: y'], lines + refused('[all]\nbuild: fails\nerror: x\n', 'no directive') + + +def test_a_leftover_option_is_a_usage_error(): + for arguments in (['--targt', 'hello'], ['--target', 'native', '--target', 'native']): + result = run(*arguments) + assert result.returncode == 2, (arguments, result) + + def test_every_case_directory_is_read(): cases = jamfiles.case_directories() assert {c.name for c in cases} >= {'hello', 'broken'}, cases diff --git a/tools/test/crypto_jamfiles_test.py b/tools/test/crypto_jamfiles_test.py index 2f9e5b11..b579cd43 100644 --- a/tools/test/crypto_jamfiles_test.py +++ b/tools/test/crypto_jamfiles_test.py @@ -33,7 +33,8 @@ # Cases whose outcome needs code that is not merged yet: a run without names leaves them out # (and says so), a run that names one builds it. Each entry names what it waits for. The -# integrator empties it when the code it waits for is merged. +# integrator empties it when the code it waits for is merged, and then rewrites the lines of those +# cases' outcome files as b2's whole output lines (a line: directive, if need be). NOT_YET = { 'has_openssl_on_emscripten': 'the refusal in config.hpp (Task 6)', 'default_openssl_on_emscripten': 'the refusal in config.hpp (Task 6)', @@ -82,7 +83,7 @@ def outcome(path: Path, target: str) -> Outcome: raise OutcomeError(f'{where}: a line before the first [block]: {raw!r}') directive = re.match(r'([a-z]+):(?: |$)', raw) key, value = (directive.group(1), raw[directive.end():]) if directive else ('', raw) - if key and key not in ('targets', 'build', 'run', 'arguments'): + if key and key not in ('targets', 'build', 'run', 'arguments', 'line'): raise OutcomeError(f'{where}: no directive {key}: (a line of one lowercase word and ' f'a colon is reserved for them): {raw!r}') if key in ('targets', 'arguments') and not value.split(): @@ -107,7 +108,7 @@ def outcome(path: Path, target: str) -> Outcome: elif key == 'arguments': result.arguments += value.split() else: - result.lines.append(raw) + result.lines.append(value if key == 'line' else raw) if target in result.targets: checked(path, target, result) return result @@ -214,6 +215,10 @@ def main(argv: list[str]) -> int: targets = [argv[position + 1]] argv = argv[:position] + argv[position + 2:] names = [a for a in argv if not a.startswith('--')] + if len(names) != len(argv): + print(f'crypto_jamfiles: no option {[a for a in argv if a.startswith("--")]}; ' + 'the one is --target ', file=sys.stderr) + return 2 try: cases = case_directories() except OutcomeError as error: diff --git a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome index af5f9f9f..355f6ab9 100644 --- a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome +++ b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome @@ -4,6 +4,8 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) +# Until Task 6 merges, this case is left out of a run (NOT_YET). When it is enabled, rewrite the +# message below as b2's whole output line(s), with a line: directive. [all] targets: emscripten build: fails diff --git a/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome index 600c34d3..aa4c9bf9 100644 --- a/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome +++ b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome @@ -4,6 +4,8 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) +# Until Task 6 merges, this case is left out of a run (NOT_YET). When it is enabled, rewrite the +# message below as b2's whole output line(s), with a line: directive. [all] targets: emscripten build: fails From 5192aca16c4a0cfc0c08d4bf20850cab0d814a29 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:57:27 -0300 Subject: [PATCH 13/59] tools: the entropy sources rule knows RDRAND, random, rand48 and mt19937 --- CODING-GUIDELINES.md | 2 +- doc/releases/0.1.0.adoc | 3 ++- tools/lint/lint.sh | 31 +++++++++++++++++++------- tools/lint/lint_test.py | 48 +++++++++++++++++++++++++---------------- 4 files changed, 56 insertions(+), 28 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 9962ad84..3141fa51 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -599,7 +599,7 @@ with `lint: failed: ` for each rule that failed. | licence notice | a source file (C++, JavaScript, AsciiDoc, Python, shell, Jam, YAML, HTML) that does not open with the notice (chapter 2) | | banned word | the word that the pattern `veru[s]` matches, in any case, in a file, a file name or a commit (its author, committer or message) of any repository | | no clock, disk or network | a library header that names a clock, a file, a socket, a process, a thread, the environment or entropy (`random_device`, `getentropy`, `getrandom`, `arc4random`, OpenSSL's `RAND_bytes`, ``) without `lint-world:` | -| entropy sources | a library header whose path ends `entropy.hpp` or `random_device.hpp` that names `rand`, `srand`, `time`, `clock` or `__rdrand`, even with `lint-world:` | +| entropy sources | a library header whose path ends `entropy.hpp` or `random_device.hpp` that names `rand`, `srand`, `random`, `rand_r`, a `rand48` function, `mt19937`, `time`, `clock` or RDRAND (`_rdrand32_step` and its kin, the builtins, `rdrand` in asm), even with `lint-world:` | | raw b2 rules | `run`, `run-fail`, `compile`, `compile-fail`, `exe`, `unit-test`, `link` or `link-fail` in a library's test or example Jamfile (`AGENTS.md` chapter 4) | | Doc Comments | a command webcpp does not allow, a bare `@`, or a colon after a reference (chapter 7) | | Pyright | an error or a warning in any Python file, with `pyrightconfig.json` (unused imports and variables are errors) | diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index feeb47a6..d91092d5 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -225,7 +225,8 @@ Emscripten's notice that the runtime is kept alive. `EM_JS` function or an `EM_ASM` block. * Added the project id /third_party, the form a user's Jamfile writes for third-party code. -* Added the lint rule entropy sources, which refuses a weaker source in a header that reads entropy. +* Added the lint rule entropy sources, which refuses a weaker source in a header that +reads entropy. [#webcpp-0-1-0-compilers-tested] == Compilers tested diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index df02046e..d5629b40 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -613,17 +613,32 @@ else printf ' the entropy\n' fi -# 8a. A header that reads entropy names no weaker source: no rand, time, clock or -# __rdrand, even with lint-world:, in any header whose path ends entropy.hpp or -# random_device.hpp (DESIGN, 2026-10-11 "entropy, safest and readable"). +# 8a. A header that reads entropy names no weaker source: no rand, random, the *rand48 family, +# mt19937, time, clock or RDRAND (the _rdrandNN_step intrinsics, the compiler builtins, or +# the instruction in inline asm), even with lint-world:, in any header whose path ends +# entropy.hpp or random_device.hpp (DESIGN, 2026-10-11 "entropy, safest and readable"). rule 'entropy sources' files_matching '^(libs|tools/test/fixtures)/[^/]+/include/.*(entropy|random_device)\.hpp$' \ > "${work_directory}/entropy_headers" -weak='(^|[^_[:alnum:]])(s?rand|time|clock|__rdrand(16|32|64)?_step|__rdrand)[[:space:]]*\(' -weak_found="$(on_files "${work_directory}/entropy_headers" grep -nHE -e "${weak}" || true)" -if [ -n "${weak_found}" ]; then - printf '%s\n' "${weak_found}" \ - | sed 's/$/: a header that reads entropy names rand, time, clock or __rdrand/' +weak_calls='s?rand|random|rand_r|[edjlmn]rand48|time|clock' +weak_rdrand='_*rdrand(16|32|64)?_step|__builtin_ia32_rdrand(16|32|64)_step' +weak='(^|[^_[:alnum:]])((('"${weak_calls}|${weak_rdrand}"')[[:space:]]*\()|(mt19937|rdrand)([^_[:alnum:]]|$))' +weak_found='' +entropy_failed=0 +while IFS= read -r -d '' entropy_header; do + entropy_status=0 + entropy_hits="$(grep -nHE -e "${weak}" "${entropy_header}")" || entropy_status=$? + if [ "${entropy_status}" -gt 1 ]; then + entropy_failed=1 # grep's own error (2) is a failure of the rule, never "no match" + elif [ "${entropy_status}" -eq 0 ]; then + weak_found+="${entropy_hits}"$'\n' + fi +done < "${work_directory}/entropy_headers" +if [ "${entropy_failed}" -ne 0 ]; then + fail "grep failed to read a header that reads entropy" +elif [ -n "${weak_found}" ]; then + printf '%s' "${weak_found}" \ + | sed 's/$/: a header that reads entropy names a weaker source/' fail "a header that reads entropy names a weaker source" else printf 'no header that reads entropy names a weaker source\n' diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 6a9c8a5c..fd54cf82 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -1719,26 +1719,38 @@ def test_world_rule(root): def test_entropy_sources(root): prepare(root) header = 'libs/demo/include/webcpp/demo/entropy.hpp' + other = 'libs/demo/include/webcpp/demo/other.hpp' # A header that reads entropy names no weaker source, even with lint-world:, which spares it # from the rule above but not from this one. getentropy is the source, not a weaker one. - write(root, header, - '// Copyright (c) 2026 WebCpp.org\n' - '//\n' - '// Distributed under the Boost Software License, Version 1.0. (See\n' - '// accompanying file LICENSE_1_0.txt or copy at\n' - '// https://www.boost.org/LICENSE_1_0.txt)\n' - '\n' - '#ifndef WEBCPP_DEMO_ENTROPY_HPP\n' - '#define WEBCPP_DEMO_ENTROPY_HPP\n' - '\n' - '// Calls rand(). lint-world: a test\n' - '// Calls getentropy(p, 16). lint-world: a test\n' - '\n' - '#endif // WEBCPP_DEMO_ENTROPY_HPP\n') - expect_alone(lint(root), 'entropy sources', [ - at(root, header, 'rand()'), - ': a header that reads entropy names rand, time, clock or __rdrand', - ], spared=(at(root, header, 'getentropy'),)) + weaker = ['rand()', 'srand(1)', 'time(nullptr)', 'clock()', '_rdrand64_step(&v)', + '__builtin_ia32_rdrand32_step(&v)', 'random()', 'rand_r(&seed)', 'drand48()', + 'nrand48(x)', 'std::mt19937 engine', '"rdrand %0"'] + lines = ''.join(f'// Calls {name}. lint-world: a test\n' for name in weaker) + + def licensed(guard: str, body: str) -> str: + return ('// Copyright (c) 2026 WebCpp.org\n' + '//\n' + '// Distributed under the Boost Software License, Version 1.0. (See\n' + '// accompanying file LICENSE_1_0.txt or copy at\n' + '// https://www.boost.org/LICENSE_1_0.txt)\n' + '\n' + f'#ifndef WEBCPP_DEMO_{guard}_HPP\n' + f'#define WEBCPP_DEMO_{guard}_HPP\n' + '\n' + f'{body}' + '\n' + f'#endif // WEBCPP_DEMO_{guard}_HPP\n') + + source = ('// Calls getentropy(p, 16). lint-world: a test\n' + '// Names random_device. lint-world: a test\n') + write(root, header, licensed('ENTROPY', lines + source)) + # Outside the rule's scope, the same names are left alone. + write(root, other, licensed('OTHER', '// Calls rand(). lint-world: a test\n')) + expect_alone(lint(root), 'entropy sources', + [at(root, header, name) for name in weaker] + + [': a header that reads entropy names a weaker source'], + spared=(at(root, header, 'getentropy'), at(root, header, 'Names random_device'), + other)) def test_bare_throw(root): From 334b83cde6fcd317a731ba6cc5b4c5d4b879e548 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:50:15 -0300 Subject: [PATCH 14/59] tools: webcpp.same-program, a library named and not called adds no byte --- AGENTS.md | 14 +++ doc/releases/0.1.0.adoc | 1 + tools/same_program/compare.py | 41 ++++++++ tools/same_program/same_program.jam | 82 ++++++++++++++++ tools/test/webcpp_jam_test.py | 146 +++++++++++++++++++++++++++- tools/webcpp.jam | 23 +++++ 6 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 tools/same_program/compare.py create mode 100644 tools/same_program/same_program.jam diff --git a/AGENTS.md b/AGENTS.md index 5906959e..7fc4d7b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1043,6 +1043,7 @@ webcpp.example : * : * ; webcpp.headers-alone : : * : * : * ; webcpp.link : + : * : * ; webcpp.link-fail : + : * : * ; +webcpp.same-program : + : : * : * ; webcpp.data + ; (requirements) webcpp.source-only + ; (reference source trees) ``` @@ -1226,6 +1227,19 @@ webcpp.generated : diff --git a/tools/doc/extensions_test.py b/tools/doc/extensions_test.py index 5783c430..0b5536c0 100755 --- a/tools/doc/extensions_test.py +++ b/tools/doc/extensions_test.py @@ -672,6 +672,103 @@ def test_style_gives_the_content_a_right_gutter_from_the_toc(_: None) -> None: assert ems(toc['width']) == ems(body['padding-left']), (media, toc, body) +def test_a_word_longer_than_any_line_breaks_at_every_width(_: None) -> None: + # A word of code longer than any line from 600px holds, 60 characters, such as a linker's + # symbol, is marked long, and the style keeps its breaks and lets it wrap at every width: + # kept whole, it would make the page wider than the screen at 900px. A word of 60 stays as a + # word a phone breaks. + symbol = 'webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link' + sixty = 'a' * 20 + '_' + 'b' * 19 + '_' + 'c' * 19 + html = body(convert(f'The link says `+{symbol}+`, `+undefined symbol: {symbol}+` and\n' + f'`{sixty}`.\n')) + broken = parts('webcpp_|crypto_|bearssl_|7bea48e_|getentropy__|add_|third_|party_|' + 'bearssl_|to_|your_|link') + assert f'{broken}' in html, html + assert (f'undefined ' + f'symbol: {broken}') in html, html + assert f'{parts("a" * 20 + "_|" + "b" * 19 + "_|" + "c" * 19)}' in html, html + rules = [(media or '', selector, declarations) + for media, selectors, declarations in page_style() + for selector in selectors if '.long' in selector] + assert sorted(rules, key=str) == sorted([ + ('', '#content code.long', {'white-space': 'normal'}), + ('', '#content code.words>span.long', {'white-space': 'normal'}), + ('screen and (min-width: 37.5em)', '#content code.long span.wbr', {'display': 'inline'}), + ('screen and (min-width: 37.5em)', '#content code.words>span.long span.wbr', + {'display': 'inline'}), + ], key=str), rules + + +def test_style_breaks_names_in_a_table_between_their_parts(_: None) -> None: + # In a table narrower than 1200px, and in a table of the role wrap-names at every width, + # inline code wraps and keeps its part breaks, so that a column is as narrow as the longest + # part of its names: a table of long names fits its page instead of scrolling from 900px to + # 1199px. A word a phone keeps whole stays whole. + rules = {(media, selector): declarations for media, selectors, declarations in page_style() + for selector in selectors} + wrapping = {'white-space': 'normal', 'overflow-wrap': 'break-word'} + for media, scope in (('screen and (max-width: 74.9375em)', 'table.tableblock'), + (None, 'table.tableblock.wrap-names')): + for selector in (f'{scope} :not(pre):not([class^=L])>code', f'{scope} code.words>span'): + assert rules.get((media, selector)) == wrapping, (media, selector) + assert rules.get(('screen and (min-width: 37.5em) and (max-width: 74.9375em)', + '#content table.tableblock code span.wbr')) == {'display': 'inline'}, rules + assert rules.get(('screen and (min-width: 37.5em)', + '#content table.tableblock.wrap-names code span.wbr')) == { + 'display': 'inline'}, rules + assert rules.get((None, '#content code.whole')) == {'white-space': 'nowrap'}, rules + html = body(convert('[.wrap-names,cols="1,1,1",options="header"]\n|===\n| A | B | C\n\n' + '| x | y | z\n|===\n')) + assert '' in html, html + + +def test_style_lifts_a_link_s_underline_off_underscores(_: None) -> None: + # A link's underline at its default height covers the underscores of a name of code, which + # then reads as words: under a link that holds code, or in code that holds a link, it is + # drawn lower. + lifted = {selector for media, selectors, declarations in page_style() + if media is None and declarations.get('text-underline-offset') == '.3em' + for selector in selectors} + assert {'#content a:has(>code)', '#content code a'} <= lifted, lifted + + +def test_a_table_too_wide_stacks_as_on_a_phone(_: None) -> None: + # A table whose columns do not fit the page stacks its rows as a phone's style does, at any + # width: the page's script measures each table's box and marks it stacked, and the style + # lays out a stacked box's table as the phone's rules lay out every table. + docinfo = (HERE / 'docinfo.html').read_text() + script = re.search(r'', docinfo, flags=re.S) + assert script, docinfo + for part in ("querySelectorAll('div.table-scroll')", "classList.remove('stacked')", + 'box.scrollWidth > box.clientWidth', "classList.add('stacked')", + "addEventListener('DOMContentLoaded', stack)", + "addEventListener('resize', stack)"): + assert part in script.group(1), (part, script.group(1)) + phone = {} + for media, selectors, declarations in page_style(): + if media == 'screen and (max-width: 56.1875em)': + for selector in selectors: + if selector.startswith('table.') and 'admonition' not in selector: + phone[selector] = declarations + stacked = {selector[len('.table-scroll.stacked>'):]: declarations + for media, selectors, declarations in page_style() if media is None + for selector in selectors if selector.startswith('.table-scroll.stacked>')} + assert phone and stacked == phone, (stacked, phone) + + +def test_detail_macros_stay_out_of_the_reference(_: None) -> None: + # A detail macro, WEBCPP__DETAIL_*, is the library's own business, as a detail + # namespace is: the shared settings exclude it, and reference.py fails a reference that + # shows one. + shared = reference.settings('demo', {'LIBRARY': 'demo', 'MACROS': 'WEBCPP_DEMO_', + 'SOURCE_ROOT': '"r"', 'DATABASE': '"d"', 'INPUT': '"i"', + 'OUTPUT': '"o"'}, None) + excluded = shared[shared.index('exclude-macros:'):].split('\n')[1:3] + assert excluded == [" - 'WEBCPP_*_HPP'", " - 'WEBCPP_*_DETAIL_*'"], excluded + text = '[#WEBCPP_DEMO_DETAIL_SEAM]\n== x\n\n[#WEBCPP_DEMO_NO_EXCEPTIONS]\n== y\n' + assert reference.detail_macros(text) == ['WEBCPP_DEMO_DETAIL_SEAM'], text + + CASES: list[Callable[[None], None]] = [ test_prose_shows_what_mrdocs_read, test_synopsis_keeps_its_links, @@ -703,6 +800,11 @@ def test_style_gives_the_content_a_right_gutter_from_the_toc(_: None) -> None: test_breaks_are_never_wbr_and_never_copied, test_style_scrolls_a_wide_table_in_its_box, test_style_gives_the_content_a_right_gutter_from_the_toc, + test_a_word_longer_than_any_line_breaks_at_every_width, + test_style_breaks_names_in_a_table_between_their_parts, + test_style_lifts_a_link_s_underline_off_underscores, + test_a_table_too_wide_stacks_as_on_a_phone, + test_detail_macros_stay_out_of_the_reference, ] diff --git a/tools/doc/mrdocs.yml.in b/tools/doc/mrdocs.yml.in index 8ca15d72..cf7a2656 100644 --- a/tools/doc/mrdocs.yml.in +++ b/tools/doc/mrdocs.yml.in @@ -32,12 +32,15 @@ implementation-defined: # Every macro of the library, WEBCPP__*, or every WEBCPP_* for config, # which holds the collection's, is extracted, so that an undocumented one is # reported; the include guards, WEBCPP__
_HPP and config's -# WEBCPP_
_HPP, are not macros of its interface. +# WEBCPP_
_HPP, are not macros of its interface, and neither is a +# detail macro, WEBCPP__DETAIL_*, the library's own business as a detail +# namespace is: the reference shows none (reference.py checks it). extract-all-macros: true include-macros: - '@MACROS@*' exclude-macros: - 'WEBCPP_*_HPP' + - 'WEBCPP_*_DETAIL_*' # What MrDocs writes: one AsciiDoc file without a document title, which the # library's page includes with leveloffset=+1, and whose links to the source diff --git a/tools/doc/postprocess.mjs b/tools/doc/postprocess.mjs index c0642b9c..9b61964c 100644 --- a/tools/doc/postprocess.mjs +++ b/tools/doc/postprocess.mjs @@ -31,6 +31,9 @@ // stacks the table's rows; a table of two columns, a name and what it is, // reads stacked without them. // +// A word of inline code too long for any line from 600px, more than 60 +// characters, is marked `long`, and the style keeps its breaks at every width. +// // A name too long for a phone's line, in inline code, in a heading of the // reference, `webcpp::xactor::scheduler::run_one`, or in a bare URL, may break // between its parts, which an empty `` marks: after a `::`, @@ -105,6 +108,13 @@ const INLINE_CODE = /((?:[^<]|]*>|<\/a>)*)<\/code>/g; // a list item or a stacked table cell narrows to about 260px. const WHOLE = 24; +// The longest word of inline code that every line from 600px holds whole: at +// 600px the content is about 565px wide, about 65 characters of the code font. +// A longer word, a linker's symbol of 80 characters, keeps its breaks between +// its parts at every width, marked `long`: kept whole, it would make the page +// wider than the screen. +const LONG = 60; + // A break after a `::`, which a heading of the reference keeps at every width; // and one between the other parts of a name, which the style keeps only on a // phone: from 600px every such name has room on a line. @@ -173,12 +183,19 @@ function isWhole(word) { return decodeEntities(textOf(word), { markup: true }).length <= WHOLE; } -// A word of inline code, as an element: `whole`, or breakable between its -// parts. +// Whether a word of inline code is longer than a line from 600px holds. +function isLong(word) { + return decodeEntities(textOf(word), { markup: true }).length > LONG; +} + +// A word of inline code, as an element: `whole`, breakable between its parts +// on a phone, or `long`, breakable between its parts at every width. function wordOf(element, word) { - return isWhole(word) - ? `<${element} class="whole">${word}` - : `<${element}>${breakableCode(word)}`; + if (isWhole(word)) { + return `<${element} class="whole">${word}`; + } + const kind = isLong(word) ? ' class="long"' : ''; + return `<${element}${kind}>${breakableCode(word)}`; } function wordsOfCode(html) { diff --git a/tools/doc/reference.py b/tools/doc/reference.py index 9a3e8d80..72cd03df 100755 --- a/tools/doc/reference.py +++ b/tools/doc/reference.py @@ -119,6 +119,12 @@ def stray_macros(text: str) -> list[str]: if not any(name == family or name.startswith(f'{family}_') for family in families)] +def detail_macros(text: str) -> list[str]: + """The detail macros, WEBCPP__DETAIL_*, of a reference, MrDocs's text: none is of the + library's interface, and mrdocs.yml.in excludes them, as a detail namespace is.""" + return [name for name in MACRO_SECTION.findall(text) if '_DETAIL_' in name] + + def macro_prefix(library: str) -> str: """The prefix of the macros the library's reference lists: WEBCPP__, or WEBCPP_ for config.""" @@ -518,6 +524,10 @@ def reference(options: argparse.Namespace) -> int: f'({", ".join(libraries.CONFIG_FAMILIES)}); a new family goes into ' 'CONFIG_FAMILIES, in tools/doc/libraries.py' for name in stray_macros(written.read_text())] + if written.is_file(): + faults += [f'reference.py: {name}: a detail macro is in the reference, which ' + 'tools/doc/mrdocs.yml.in excludes' + for name in detail_macros(written.read_text())] try: found = doc_comments.check(clang, library, include, [*flags, f'-I{include}', *systems, str(aggregate)], From 29d0e69dcc5ed6fedd21ecb1d59c0231d5af4c4a Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 16:00:25 -0300 Subject: [PATCH 52/59] tools/release: the changelog rule refuses an inline anchor, [[...]] or anchor:, which shows no text: crypto's [[nodiscard]] was missing from its line --- AGENTS.md | 4 +++- CODING-GUIDELINES.md | 2 +- doc/releases/0.1.0.adoc | 1 + tools/release/changelog.py | 21 +++++++++++++++--- tools/release/changelog_test.py | 39 +++++++++++++++++++++++++++++---- 5 files changed, 58 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6ae1db1d..2a14e444 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1977,7 +1977,9 @@ superproject's new `main`. `main` is the only branch. a fixed bug names the symptom, with its issue or pull request when there is one, `https://github.com/webcpporg//issues/[#]`. A line holds no cross-reference, `<<...>>`: the index page shows it too, where the - library's anchors are not. + library's anchors are not. Nor does it hold an inline anchor, `[[...]]`, + which shows no text: a C++ attribute is passthrough code, + `` `+[[nodiscard]]+` ``. - **At most ten lines per library and version,** the most important first; a version's documentation work is one line. A library's change that no user sees (a test, its CI, a refactoring) gets none. diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index be29415b..f28833f3 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -648,7 +648,7 @@ with `lint: failed: ` for each rule that failed. | path.exists native | a `path.exists` of a Jam file given a path other than `[ path.native ... ]`: b2's builtin asks the system about the path as written, and b2's form of a Windows path, `/D:/a/...`, names no file there | | include boundaries | an `#include` that crosses a boundary the library declares in its `meta/include-boundaries.json` (below), at its line, with the boundary's reason; and a malformed file, or a glob that matches no file of the library | | bare throw | a `throw` expression in a library's public header (`libs/*/include/**`), outside comments and literals, at its line: inside `#ifndef WEBCPP__NO_EXCEPTIONS` too, in a template that nothing instantiates, which clang-tidy's analysis without exceptions does not see, and as a rethrow, `throw;`; `boost::throw_exception` is the one way to raise, `std::rethrow_exception` the one way to rethrow (above) | -| changelog form | a library's changelog or a version's release notes out of `AGENTS.md` chapter 5's form: a section or a region missing or out of order, a line that starts with no verb of the list, a cross-reference, more than ten lines for a library and a version, text outside a bullet | +| changelog form | a library's changelog or a version's release notes out of `AGENTS.md` chapter 5's form: a section or a region missing or out of order, a line that starts with no verb of the list, a cross-reference, an inline anchor such as `[[nodiscard]]` outside a passthrough, more than ten lines for a library and a version, text outside a bullet | | canary pins | a `WEBCPP_CRYPTO__COMMIT` of crypto's `detail/canary.h` that is not the first seven digits of the commit the superproject records for its submodule (`ctaes`: `bitcoin`) | | nodiscard results | a function of a library's `include/` that returns `boost::system::result` without `[[nodiscard]]`, at its line, when the library asks for the rule in its `meta/lint.json` (`"nodiscard-results"` and its reason; crypto does): `boost::system::result` carries no `[[nodiscard]]` of its own; and a malformed file or an unknown key | diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index c7f63307..c11285d1 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -75,6 +75,7 @@ None. * Fixed BearSSL's entropy defines on a Windows target built by Clang or GCC. * Added the lint rule nodiscard results, which a library asks for in its meta/lint.json. * Changed the pages' tables to stack as on a phone when they do not fit, and long names in them to break between their parts. +* Added the changelog rule's refusal of inline anchors, which hid a {cpp} attribute from its line. * Fixed links over code hiding the underscores of names under their underline. * Changed the references to leave out detail macros, WEBCPP_*_DETAIL_*. * Fixed the WASIp2 test launcher interrupting large finite workloads after 60 seconds. diff --git a/tools/release/changelog.py b/tools/release/changelog.py index b397e8a9..2cd2013a 100755 --- a/tools/release/changelog.py +++ b/tools/release/changelog.py @@ -25,7 +25,8 @@ (+, ----, [source] and the like) or a directive (include::, ifdef::) inside a region fails. It starts with one of VERBS, or with "*Breaking change:* " and then one of VERBS, whose first letter may be lower case, holds the prefix nowhere else, holds at most WORDS words, and holds no -cross-reference, <<...>>, xref: or link:#, since the index page shows it too. A library's +cross-reference, <<...>>, xref: or link:#, since the index page shows it too, and no inline +anchor, [[...]] or anchor:, which shows no text (a C++ attribute is `+[[nodiscard]]+`). A library's version holds at most MOST of them; the sections of release notes have no such limit. Outside its regions, a library's changelog holds no bullet, and no text after its first section. @@ -78,6 +79,9 @@ # A cross-reference as Asciidoctor finds one, in a code span too, once its passthroughs are out. CROSS_REFERENCE = re.compile(r'<<[\w#/.:{].*?>>|\bxref:[\w#/.:{][^\s\[]*\[|\blink:#[^\s\[]*\[') PASSTHROUGH = re.compile(r'\+[^+]*\+') +# An inline anchor as Asciidoctor finds one, in a code span too, once its passthroughs are out: +# [[id]] or [[id,text]], whose id may hold colons, as a C++ attribute does, and anchor:id[]. +INLINE_ANCHOR = re.compile(r'\[\[[^\W\d][\w:.-]*(?:,[^\]]*)?\]\]|\banchor:[^\W\d][\w:.-]*\[') Finding = tuple[int, str] @@ -162,6 +166,17 @@ def cross_references(bullet: Bullet) -> list[Finding]: 'page shows it too')] +def anchors(bullet: Bullet) -> list[Finding]: + """An inline anchor the line holds: Asciidoctor renders it as an empty element, so that its + text, a C++ attribute such as [[nodiscard]], is missing from the line, and the index page, + showing the line too, holds its id twice.""" + if INLINE_ANCHOR.search(PASSTHROUGH.sub('', bullet.text)) is None: + return [] + return [(bullet.line, 'a line holds no anchor, [[...]] or anchor:, which shows no text and ' + 'whose id the index page repeats: a C++ attribute is code, ' + '`+[[nodiscard]]+`')] + + def line_findings(bullet: Bullet) -> list[Finding]: """What breaks a line's form.""" findings: list[Finding] = [] @@ -180,7 +195,7 @@ def line_findings(bullet: Bullet) -> list[Finding]: if words > WORDS: findings.append((bullet.line, f'a line holds at most {WORDS} words, and this one holds ' f'{words}: {bullet.text}')) - return findings + cross_references(bullet) + return findings + cross_references(bullet) + anchors(bullet) def section_starts(lines: list[str], index: int) -> bool: @@ -337,7 +352,7 @@ def listed(slug: str, pattern: re.Pattern[str]) -> list[tuple[str, str]]: if match is None: findings.append((item.line, f'not a line of {slug}: {item.text}')) else: - findings.extend(cross_references(item)) + findings.extend(cross_references(item) + anchors(item)) entries.append((match.group('name'), match.group('what'))) return entries diff --git a/tools/release/changelog_test.py b/tools/release/changelog_test.py index 76b6d1e1..26c27b52 100755 --- a/tools/release/changelog_test.py +++ b/tools/release/changelog_test.py @@ -7,10 +7,10 @@ """Checks tools/release/changelog.py: a library's changelog and a version's release notes in AGENTS.md chapter 5's form pass, wrapped lines included; a line with no verb of the list, a -cross-reference, an eleventh line, text outside a bullet, a section out of order or without its -region, and notes out of form each fail, at their line. The reader reads a list as the doc -build's Asciidoctor.js renders it, which tools/node/install.py installs when it is not there. -Run with the names of some cases to run only those.""" +cross-reference, an inline anchor, an eleventh line, text outside a bullet, a section out of +order or without its region, and notes out of form each fail, at their line. The reader reads a +list as the doc build's Asciidoctor.js renders it, which tools/node/install.py installs when it +is not there. Run with the names of some cases to run only those.""" from __future__ import annotations @@ -30,6 +30,8 @@ VERB_LIST = 'Added, Changed, Deprecated, Fixed, Improved, Removed, Updated' CROSS_REFERENCE = ('a line holds no cross-reference, <<...>>, xref: or link:#: the index page ' 'shows it too') +ANCHOR = ('a line holds no anchor, [[...]] or anchor:, which shows no text and whose id the index ' + 'page repeats: a C++ attribute is code, `+[[nodiscard]]+`') NESTED = ('a line of a changelog is a bullet at the margin, "* ", with no nested list, block, ' 'attribute or directive: ') @@ -138,6 +140,12 @@ def links_into_the_page(self) -> list[str]: return [target for target in own if target.startswith('#')] + [ target for child in self.elements() for target in child.links_into_the_page()] + def anchors(self) -> list[str]: + """The ids of the anchors this element holds, at any depth: an with an id.""" + own = [self.attributes.get('id') or ''] if self.tag == 'a' and 'id' in self.attributes \ + else [] + return own + [anchor for child in self.elements() for anchor in child.anchors()] + class Tree(HTMLParser): """The tree of elements of an HTML text.""" @@ -269,6 +277,28 @@ def test_cross_references_as_asciidoctor_reads_them() -> None: assert changelog.changelog_findings(text, 'alpha') == expected, line +def test_anchors_as_asciidoctor_reads_them() -> None: + # An inline anchor renders an empty , in a code span too: the line loses the text and + # the index page, which shows the line, gets the id twice. A C++ attribute in a passthrough, + # +...+, is code. + anchored = ['* Added every result [[nodiscard]].', '* Added `[[nodiscard]]` results.', + '* Added [[alpha-x,the x]]x.', '* Added anchor:alpha-x[] x.', + '* Added `[[gnu::always_inline]]`.'] + plain = ['* Added every result `+[[nodiscard]]+`.', '* Added +[[maybe_unused]]+ names.', + '* Added `+std::array{{1, 2}}+`.', '* Added `a[b[0]]`.'] + rendered = asciidoctor(''.join(f'== Case {number}\n\n{line}\n\n' + for number, line in enumerate(anchored + plain))) + sections = [section for section in rendered.elements() if section.kind == 'sect1'] + for line, section in zip(anchored + plain, sections): + assert bool(section.elements()[1].anchors()) == (line in anchored), line + text = log('alpha', ('Unreleased', [line])) + expected = [(line_of(text, line), ANCHOR)] if line in anchored else [] + assert changelog.changelog_findings(text, 'alpha') == expected, line + tools = '* Added the rule [[nodiscard]].' + text = notes(tools=tools) + assert findings_of(text) == [(line_of(text, tools), ANCHOR)] + + def test_text_outside_every_region_fails() -> None: # A line after a region's end shows on the page, but no release note includes it; so does a # bullet among the opening paragraphs. Before [appendix], only the notice may come. @@ -510,6 +540,7 @@ def test_the_tree_s_changelogs_keep_their_form() -> None: test_text_outside_a_bullet_and_a_cross_reference_fail, test_a_breaking_change_goes_on_with_a_verb, test_cross_references_as_asciidoctor_reads_them, + test_anchors_as_asciidoctor_reads_them, test_text_outside_every_region_fails, test_sections_in_order_each_with_its_region, test_each_section_named_as_its_title, From 9e643a7d6a198f46808bd19b03e3a58cbdb4fb84 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 16:00:25 -0300 Subject: [PATCH 53/59] tools/doc: a table breaks its names only when it does not fit with them whole, and stacks only after that; a matrix of eight columns or more scrolls in its box rather than stack; the measure runs again on load and once the fonts are ready; the roles keep and key-column; the table of contents breaks a name after its :: --- doc/releases/0.1.0.adoc | 3 ++ tools/doc/docinfo.html | 65 +++++++++++++++++------- tools/doc/extensions_test.py | 98 +++++++++++++++++++++++++++++------- tools/doc/postprocess.mjs | 57 +++++++++++++++++++-- 4 files changed, 184 insertions(+), 39 deletions(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index c11285d1..250195e8 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -75,6 +75,9 @@ None. * Fixed BearSSL's entropy defines on a Windows target built by Clang or GCC. * Added the lint rule nodiscard results, which a library asks for in its meta/lint.json. * Changed the pages' tables to stack as on a phone when they do not fit, and long names in them to break between their parts. +* Changed the pages' tables to keep names whole where they fit, and a table of eight columns or more to scroll rather than stack. +* Added the role key-column, which keeps a table's first column wide enough for its words. +* Fixed the table of contents breaking a name of the reference between two of its letters. * Added the changelog rule's refusal of inline anchors, which hid a {cpp} attribute from its line. * Fixed links over code hiding the underscores of names under their underline. * Changed the references to leave out detail macros, WEBCPP_*_DETAIL_*. diff --git a/tools/doc/docinfo.html b/tools/doc/docinfo.html index d9ddcc56..2c4b9bb2 100644 --- a/tools/doc/docinfo.html +++ b/tools/doc/docinfo.html @@ -98,26 +98,41 @@ @media screen and (min-width: 37.5em) { #content :not(pre):not([class^=L]) > code span.wbr, span.wbr.part { display: none; } } -/* In a table narrower than 1200px, and in a table of the role wrap-names at every width, a name - longer than a phone's word breaks between its parts, where postprocess.mjs marks them, and a - part still wider than its column where it must: a column is then as narrow as the longest part - of its names, not as the longest name, and the table fits its page rather than scroll. From - 1200px a table keeps its names whole, as its columns have room for them; wrap-names is for a - table whose names would leave its key column of prose too narrow. A name a phone keeps whole, - code.whole, stays whole in a table too. A table that does not fit even so stacks (below). */ +/* Below 1200px a name in a table wraps, which a part wider than its column breaks where it must, + as before any of the rules below. A table too wide for its box with its names whole, whose + box the script below marks parts, and a table of the role wrap-names at every width, break a + name longer than a phone's word between its parts too, where postprocess.mjs marks them, and + a part still wider than its column where it must: a column is then as narrow as the longest + part of its names, not as the longest name, and the table fits its page rather than scroll. A + table that fits keeps its names whole, as their columns have room for them; wrap-names is for + a table whose names would leave its key column of prose too narrow. A name a phone keeps + whole, code.whole, stays whole in a table too. A table that does not fit even so stacks + (below). */ @media screen and (max-width: 74.9375em) { table.tableblock :not(pre):not([class^=L]) > code, table.tableblock code.words > span { white-space: normal; overflow-wrap: break-word; } } -@media screen and (min-width: 37.5em) and (max-width: 74.9375em) { - #content table.tableblock code span.wbr { display: inline; } -} +.table-scroll.parts > table.tableblock :not(pre):not([class^=L]) > code, +.table-scroll.parts > table.tableblock code.words > span, table.tableblock.wrap-names :not(pre):not([class^=L]) > code, table.tableblock.wrap-names code.words > span { white-space: normal; overflow-wrap: break-word; } @media screen and (min-width: 37.5em) { + #content .table-scroll.parts > table.tableblock code span.wbr, #content table.tableblock.wrap-names code span.wbr { display: inline; } } #content code.whole, #content code.words > span.whole { white-space: nowrap; } +/* Inline code of the role keep, such as a target or a file a reader copies, stays on one line at + every width, in a table too: postprocess.mjs marks no part in it. */ +#content code.keep { white-space: nowrap; } +/* A table of the role key-column keeps room for a few words a line in its first column, the one + a reader starts from: without it, at 1199px, "I need to" of crypto's decision table is three + words wide, its other columns as wide as their names. Where the table does not fit with that + room and its names whole, its box marked parts, the names of its other columns break between + their parts, short names too, where postprocess.mjs marks them in such a table, but those of + the role keep. */ +table.tableblock.key-column > tbody > tr > td:first-child { min-width: 10em; } +#content .table-scroll.parts > table.key-column code.whole, +#content .table-scroll.parts > table.key-column code.words > span.whole { white-space: normal; } /* A word of code longer than any line from 600px holds, code.long (postprocess.mjs), such as a linker's symbol, breaks between its parts at every width: kept whole, it would make the page wider than the screen. */ @@ -174,7 +189,10 @@ /* Wider than a phone, a table whose columns do not fit the page even with its names broken between their parts stacks its rows as a phone's do: the script below marks its box stacked, since only a measure tells whether a table fits. A table that fits is laid out as a table; - without the script, one that does not scrolls in its box. */ + without the script, one that does not scrolls in its box. A matrix, a table of eight columns + or more, such as a benchmark's or a profile's, is read down its columns as much as along its + rows: stacked, each row would be a card of eight lines or more and its columns could no + longer be compared, so wider than a phone it stays a table and scrolls in its box. */ .table-scroll.stacked > table.tableblock, .table-scroll.stacked > table.tableblock > tbody, .table-scroll.stacked > table.tableblock > tbody > tr, .table-scroll.stacked > table.tableblock > tbody > tr > td, @@ -194,18 +212,29 @@ } diff --git a/tools/doc/extensions_test.py b/tools/doc/extensions_test.py index 0b5536c0..dec3288a 100755 --- a/tools/doc/extensions_test.py +++ b/tools/doc/extensions_test.py @@ -52,16 +52,18 @@ def installed() -> None: check=True) -def convert(text: str) -> str: +def convert(text: str, *attributes: str) -> str: """The HTML Asciidoctor.js writes for the AsciiDoc text, with the extensions and the options - of webcpp.doc.""" + of webcpp.doc, and the attributes given, each name=value.""" with tempfile.TemporaryDirectory(prefix='doc extensions ') as scratch: source = Path(scratch) / 'page.adoc' source.write_text(HEADER + text) output = Path(scratch) / 'page.html' command = ['node', str(ASCIIDOCTOR), '-r', str(HERE / 'highlighter.mjs'), '-r', str(HERE / 'postprocess.mjs'), '-v', '--failure-level', 'INFO', '-S', 'unsafe', - '-a', 'source-highlighter=hljs-static', '-o', str(output), str(source)] + '-a', 'source-highlighter=hljs-static', + *[part for attribute in attributes for part in ('-a', attribute)], + '-o', str(output), str(source)] completed = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False) assert completed.returncode == 0, completed.stdout @@ -533,8 +535,8 @@ def test_admonitions_wrap_their_row_in_tbody(_: None) -> None: def css_rules(text: str) -> list[tuple[str | None, list[str], dict[str, str]]]: - """The rules of a stylesheet, each as its media query (None outside one), its selectors and - its declarations.""" + """The rules of a stylesheet, each as its media query (None outside one), or its container + query with its @container, its selectors and its declarations.""" text = re.sub(r'/\*.*?\*/', '', text, flags=re.S) rules: list[tuple[str | None, list[str], dict[str, str]]] = [] @@ -545,12 +547,14 @@ def read(block: str, media: str | None) -> None: if opening < 0: return prelude = block[position:opening].strip() - if prelude.startswith('@media'): + if prelude.startswith(('@media', '@container')): depth, end = 1, opening + 1 while depth: depth += {'{': 1, '}': -1}.get(block[end], 0) end += 1 - read(block[opening + 1:end - 1], prelude[len('@media'):].strip()) + # A media query as itself, a container query with its @container. + query = prelude.removeprefix('@media').strip() + read(block[opening + 1:end - 1], ' '.join(query.split())) position = end continue closing = block.index('}', opening) @@ -700,22 +704,24 @@ def test_a_word_longer_than_any_line_breaks_at_every_width(_: None) -> None: def test_style_breaks_names_in_a_table_between_their_parts(_: None) -> None: - # In a table narrower than 1200px, and in a table of the role wrap-names at every width, - # inline code wraps and keeps its part breaks, so that a column is as narrow as the longest - # part of its names: a table of long names fits its page instead of scrolling from 900px to - # 1199px. A word a phone keeps whole stays whole. + # A table too wide for its box with its names whole, which the page's script marks parts, + # and a table of the role wrap-names at every width, wrap their inline code and keep its part + # breaks, so that a column is as narrow as the longest part of its names: a table of long + # names fits its page instead of scrolling. A table that fits keeps its names whole, as it + # did before the script, from 600px. A word a phone keeps whole stays whole. rules = {(media, selector): declarations for media, selectors, declarations in page_style() for selector in selectors} wrapping = {'white-space': 'normal', 'overflow-wrap': 'break-word'} for media, scope in (('screen and (max-width: 74.9375em)', 'table.tableblock'), + (None, '.table-scroll.parts>table.tableblock'), (None, 'table.tableblock.wrap-names')): for selector in (f'{scope} :not(pre):not([class^=L])>code', f'{scope} code.words>span'): assert rules.get((media, selector)) == wrapping, (media, selector) - assert rules.get(('screen and (min-width: 37.5em) and (max-width: 74.9375em)', - '#content table.tableblock code span.wbr')) == {'display': 'inline'}, rules - assert rules.get(('screen and (min-width: 37.5em)', - '#content table.tableblock.wrap-names code span.wbr')) == { - 'display': 'inline'}, rules + live = {selector for (media, selector), declarations in rules.items() + if declarations == {'display': 'inline'} and 'wbr' in selector + and media == 'screen and (min-width: 37.5em)' and 'long' not in selector} + assert live == {'#content .table-scroll.parts>table.tableblock code span.wbr', + '#content table.tableblock.wrap-names code span.wbr'}, live assert rules.get((None, '#content code.whole')) == {'white-space': 'nowrap'}, rules html = body(convert('[.wrap-names,cols="1,1,1",options="header"]\n|===\n| A | B | C\n\n' '| x | y | z\n|===\n')) @@ -739,10 +745,18 @@ def test_a_table_too_wide_stacks_as_on_a_phone(_: None) -> None: docinfo = (HERE / 'docinfo.html').read_text() script = re.search(r'', docinfo, flags=re.S) assert script, docinfo - for part in ("querySelectorAll('div.table-scroll')", "classList.remove('stacked')", + for part in ("querySelectorAll('div.table-scroll')", 'box.scrollWidth > box.clientWidth', "classList.add('stacked')", "addEventListener('DOMContentLoaded', stack)", - "addEventListener('resize', stack)"): + "addEventListener('resize', stack)", + # The web fonts and images change the widths without a resize. + "addEventListener('load', stack)", 'document.fonts?.ready.then(stack)', + # A table breaks its names between their parts before it stacks, and only + # when it does not fit with them whole. + "classList.remove('parts', 'stacked')", "classList.add('parts')", + # A matrix, of eight columns or more, scrolls in its box rather than stack. + 'const MATRIX = 8;', "':scope > table > colgroup > col'", + 'columns(box) < MATRIX && wide(box)'): assert part in script.group(1), (part, script.group(1)) phone = {} for media, selectors, declarations in page_style(): @@ -756,6 +770,52 @@ def test_a_table_too_wide_stacks_as_on_a_phone(_: None) -> None: assert phone and stacked == phone, (stacked, phone) +def test_a_key_column_keeps_room_for_its_words(_: None) -> None: + # A table of the role key-column keeps room in its first column, at every width, for the + # words a reader starts from: crypto's decision table. Its other columns' names, short ones + # too, which stay whole elsewhere, break between their parts where it does not fit + # otherwise (the page's script marks its box parts) to make that room. + rules = {selector: declarations for media, selectors, declarations in page_style() + if media is None for selector in selectors} + assert rules.get('table.tableblock.key-column>tbody>tr>td:first-child') == \ + {'min-width': '10em'}, rules + # Inline code of the role keep, a target or a file a reader copies, stays on one line at + # every width: postprocess.mjs marks no part in it. + assert rules.get('#content code.keep') == {'white-space': 'nowrap'}, rules + kept = body(convert('[.keep]`+/third_party//ctaes+` and <>\n\n' + '[#x]\n== X\n')) + assert '/third_party//ctaes' in kept, kept + assert 'a_b.cpp' in kept, kept + for selector in ('#content .table-scroll.parts>table.key-column code.whole', + '#content .table-scroll.parts>table.key-column code.words>span.whole'): + assert rules.get(selector) == {'white-space': 'normal'}, (selector, rules) + source = ('|===\n| A | B | C\n\n| a | `+/third_party//ctaes+` ' + '| `+x+` and `+aes256+`\n|===\n') + html = body(convert('[.wrap-names.key-column,cols="1,1,1",options="header"]\n' + source + + '\n[cols="1,1,1",options="header"]\n' + source)) + keyed, plain = html.split('
')[:2] + assert 'class="tableblock frame-all grid-all stretch wrap-names key-column"' in keyed, keyed + part = '' + assert f'/third_{part}party//{part}ctaes' in keyed, keyed + assert f'aes256{part}<backends::ctaes>' \ + '' in keyed, keyed + assert 'x' in keyed, keyed + assert '/third_party//ctaes' in plain, plain + assert 'aes256<backends::ctaes>' in plain, plain + + +def test_the_table_of_contents_breaks_a_name_after_its_scopes(_: None) -> None: + # An entry of the table of contents at the side, about 14em wide, breaks a name of the + # reference after a ::, as the name's heading does, rather than between two of its letters, + # `webcpp::crypto::ciphers::ae` and `s256_gcm`. Its other parts and its code stay as written. + page = convert('== webcpp::crypto::ciphers::aes256_gcm\n\n' + '== Ciphers: `webcpp::crypto::ciphers`\n\n== Boost.Hash2 and a_b\n', 'toc=left') + toc = page[page.index('
')] + assert f'>webcpp::{SCOPE}crypto::{SCOPE}ciphers::{SCOPE}aes256_gcm' in toc, toc + assert '>Ciphers: webcpp::crypto::ciphers' in toc, toc + assert '>Boost.Hash2 and a_b' in toc, toc + + def test_detail_macros_stay_out_of_the_reference(_: None) -> None: # A detail macro, WEBCPP__DETAIL_*, is the library's own business, as a detail # namespace is: the shared settings exclude it, and reference.py fails a reference that @@ -804,6 +864,8 @@ def test_detail_macros_stay_out_of_the_reference(_: None) -> None: test_style_breaks_names_in_a_table_between_their_parts, test_style_lifts_a_link_s_underline_off_underscores, test_a_table_too_wide_stacks_as_on_a_phone, + test_a_key_column_keeps_room_for_its_words, + test_the_table_of_contents_breaks_a_name_after_its_scopes, test_detail_macros_stay_out_of_the_reference, ] diff --git a/tools/doc/postprocess.mjs b/tools/doc/postprocess.mjs index 9b61964c..4fc2beaf 100644 --- a/tools/doc/postprocess.mjs +++ b/tools/doc/postprocess.mjs @@ -34,8 +34,13 @@ // A word of inline code too long for any line from 600px, more than 60 // characters, is marked `long`, and the style keeps its breaks at every width. // +// In a table of the role key-column, a word marked `whole` has its parts +// marked too, which the style breaks between only where the table does not fit +// with its names whole, so that the table's first column keeps room for its +// words. +// // A name too long for a phone's line, in inline code, in a heading of the -// reference, `webcpp::xactor::scheduler::run_one`, or in a bare URL, may break +// reference (and its entry in the table of contents, after a `::` only), `webcpp::xactor::scheduler::run_one`, or in a bare URL, may break // between its parts, which an empty `` marks: after a `::`, // a `_`, a `/`, or a `.` between letters, before the `(` or the `<` that ends // a name, and in code between the words of a name in camel case. So a phone @@ -213,6 +218,21 @@ function wordsOfCode(html) { }); } +// A word of inline code a phone keeps whole, as code or as a word of code. +const WHOLE_WORD = /<(code|span) class="whole">((?:(?!<\/\1>)[\s\S])*?)<\/\1>/g; + +// Each table of the role key-column, its words of code marked whole made +// breakable between their parts: the style keeps them whole but where the +// table does not fit with them whole (docinfo.html). +function partsOfKeyColumnTables(html) { + return html.replace(TABLE, (table) => + /^]*\sclass="[^"]*\bkey-column\b/.test(table) + ? table.replace(WHOLE_WORD, (_word, element, text) => + `<${element} class="whole">${breakableCode(text)}`) + : table + ); +} + // A bare URL, which Asciidoctor writes as the text of its link, and which holds // no break yet: one in a heading has its breaks already. const BARE_URL = /()([^<]*)(<\/a>)/g; @@ -307,6 +327,35 @@ function boxedTables(html) { }); } +// The table of contents at the side of the page, up to the content, and the +// text of a link of it. +const TOC = /
)/; +const TOC_LINK = /()([\s\S]*?)(<\/a>)/g; + +// An entry of the table of contents, about 14em wide at the side of the page, +// breaks a name of the reference after each `::`, as the name's heading does, +// rather than between two of its letters where it must: its text outside its +// inline code, whose breaks wordsOfCode marked, and only after a `::`, which +// the style keeps at every width. +function scopesOfContents(html) { + return html.replace(TOC, (toc) => + toc.replace(TOC_LINK, (_link, open, inner, close) => { + let code = false; + const broken = inner + .split(TAG) + .map((part, index) => { + if (index % 2 === 1) { + code = /^/.test(part)); + return part; + } + return code ? part : breakable(part, [BREAKS[0]]); + }) + .join(''); + return open + broken + close; + }) + ); +} + // A heading, with what it holds. const HEADING = /(]*>)([\s\S]*?)(<\/h\2>)/g; @@ -401,8 +450,10 @@ function curledApostrophes(html) { class Page extends Postprocessor { process(_document, output) { - const page = labelledTables(wordsOfCode(decodeEntities(output))); - const built = curledApostrophes(boxedTables(partsOfURLs(partsOfHeadings(page)))); + const page = labelledTables(partsOfKeyColumnTables(wordsOfCode(decodeEntities(output)))); + const built = curledApostrophes( + boxedTables(partsOfURLs(scopesOfContents(partsOfHeadings(page)))) + ); return tbodied(styledColumns(silentAnchors(built))); } } From 10d8b9b97d5390dab510132c2fe5fb4f614961a8 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 17:21:36 -0300 Subject: [PATCH 54/59] tools/doc: a table's names break after their :: and a path's / before they break at a _ or a -, and a key-column table stacks rather than break them so; code in a table wraps only where postprocess.mjs marks a break; a matrix's first column, and a key-column table's, keep their hyphenated keys whole, a matrix's 9em wide --- doc/releases/0.1.0.adoc | 2 + tools/doc/doc-check.py | 7 +- tools/doc/doc_check_test.py | 5 +- tools/doc/docinfo.html | 128 ++++++++++++++----------- tools/doc/extensions_test.py | 180 ++++++++++++++++++++++++----------- tools/doc/postprocess.mjs | 65 +++++++++++-- 6 files changed, 263 insertions(+), 124 deletions(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 250195e8..484472e6 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -78,6 +78,8 @@ None. * Changed the pages' tables to keep names whole where they fit, and a table of eight columns or more to scroll rather than stack. * Added the role key-column, which keeps a table's first column wide enough for its words. * Fixed the table of contents breaking a name of the reference between two of its letters. +* Fixed names of code in tables breaking at an underscore or a hyphen where a break after their :: or a path's / made the table fit. +* Fixed a matrix's or a key-column table's first column breaking a hyphenated key, such as a profile's name, into a line per part. * Added the changelog rule's refusal of inline anchors, which hid a {cpp} attribute from its line. * Fixed links over code hiding the underscores of names under their underline. * Changed the references to leave out detail macros, WEBCPP_*_DETAIL_*. diff --git a/tools/doc/doc-check.py b/tools/doc/doc-check.py index a5dc6454..b54e0358 100755 --- a/tools/doc/doc-check.py +++ b/tools/doc/doc-check.py @@ -232,9 +232,10 @@ # The inline code MrDocs writes for what it links, the whole of the code one link: a symbol's # name, to its section of the page, in a table of members, or the header where a symbol is # declared, between < and >, to its line in the library's repository (mrdocs.yml.in's base-url), -# its text the header's path; postprocess.mjs breaks either between its parts. -BREAK = re.compile(r'') -LINK_TEXT = r'(?:[^<]|)*' +# its text the header's path; postprocess.mjs breaks either between its parts, a path after its +# / (part path). +BREAK = re.compile(r'') +LINK_TEXT = r'(?:[^<]|)*' SECTION_LINK = re.compile(rf'^]*">{LINK_TEXT}$') HEADER_LINK = re.compile(rf'^<]+/include/([^"#<>]+)#L[0-9]+">({LINK_TEXT})>$') diff --git a/tools/doc/doc_check_test.py b/tools/doc/doc_check_test.py index 593285be..47fd6de4 100755 --- a/tools/doc/doc_check_test.py +++ b/tools/doc/doc_check_test.py @@ -465,8 +465,9 @@ def check_rendered(root: Path) -> None: # which are no dash, and a reference whose digits go on, U+2014B; and a style and a # comment, which are no text, naming a and holding a link in code. '

Declared in <webcpp/demo/box.hpp>, ' + 'include/webcpp/demo/box.hpp#L7">webcpp/demo/box.hpp>, ' + '' 'webcpp::demo::' 'box, box, ' 'xn--bcher, a - b​ and 𠅋.

' diff --git a/tools/doc/docinfo.html b/tools/doc/docinfo.html index 2c4b9bb2..29d5eaa9 100644 --- a/tools/doc/docinfo.html +++ b/tools/doc/docinfo.html @@ -76,9 +76,8 @@ overflow-wrap: break-word; } /* Inline code breaks between its words (postprocess.mjs), never inside one, at a hyphen as - `--recursive` would or elsewhere, on a screen wide enough for its longest word. In a table on - a narrower screen it breaks inside a word only where the word alone is wider than its column - can be, so a column keeps room for a name of the reference, `answer`, whole. A word short enough + `--recursive` would or elsewhere, on a screen wide enough for its longest word; in a table at + every width, where it breaks only as the table's box allows (below). A word short enough for a phone's line, which postprocess.mjs marks whole, stays on one line at any width: without it, a phone would break `#xactor-invariant-13` at a hyphen though the word fits the line. On a phone, a longer word breaks between its parts, at the span.wbr postprocess.mjs marks, whose @@ -98,44 +97,53 @@ @media screen and (min-width: 37.5em) { #content :not(pre):not([class^=L]) > code span.wbr, span.wbr.part { display: none; } } -/* Below 1200px a name in a table wraps, which a part wider than its column breaks where it must, - as before any of the rules below. A table too wide for its box with its names whole, whose - box the script below marks parts, and a table of the role wrap-names at every width, break a - name longer than a phone's word between its parts too, where postprocess.mjs marks them, and - a part still wider than its column where it must: a column is then as narrow as the longest - part of its names, not as the longest name, and the table fits its page rather than scroll. A - table that fits keeps its names whole, as their columns have room for them; wrap-names is for - a table whose names would leave its key column of prose too narrow. A name a phone keeps - whole, code.whole, stays whole in a table too. A table that does not fit even so stacks - (below). */ -@media screen and (max-width: 74.9375em) { - table.tableblock :not(pre):not([class^=L]) > code, - table.tableblock code.words > span { white-space: normal; overflow-wrap: break-word; } -} -.table-scroll.parts > table.tableblock :not(pre):not([class^=L]) > code, -.table-scroll.parts > table.tableblock code.words > span, -table.tableblock.wrap-names :not(pre):not([class^=L]) > code, -table.tableblock.wrap-names code.words > span { white-space: normal; overflow-wrap: break-word; } -@media screen and (min-width: 37.5em) { - #content .table-scroll.parts > table.tableblock code span.wbr, - #content table.tableblock.wrap-names code span.wbr { display: inline; } +/* In a table, a name of code breaks only where the page's script finds the table too wide for + its box with its names whole, and then in two steps: first only after a :: and between two + names, never inside a word, such as at the _ of `aes256_gcm` or the - of an example's name; + then, only where the table is too wide even so, between the other parts of its names too, where + postprocess.mjs marks them, a column then as narrow as the longest part of its names. Its box + marked names, then parts, by the script. A name stays on one line between those breaks: the + style keeps inline code in a table on one line at every width, and a break postprocess.mjs + marks is the one place it wraps, its zero-width space breaking the line where the break is + live. A table of the role wrap-names keeps its breaks after a :: live at every width; one of + the role key-column breaks short names too, which postprocess.mjs marks in such a table. A + table still too wide stacks (below); one stacked and still wider than its box, for a part wider + than a card, its box marked loose, lets its code wrap where it must, as prose does. */ +#content table.tableblock :not(pre):not([class^=L]) > code, +#content table.tableblock code.words > span { white-space: nowrap; } +#content table.tableblock :not(pre):not([class^=L]) > code.words { white-space: normal; } +#content table.tableblock code span.wbr { display: none; white-space: normal; } +#content .table-scroll.names > table.tableblock code span.wbr:not(.part), +#content .table-scroll.names > table.tableblock code span.wbr.path, +#content table.tableblock.wrap-names code span.wbr:not(.part), +#content table.tableblock.wrap-names code span.wbr.path, +#content .table-scroll.parts > table.tableblock code span.wbr { display: inline; } +#content .table-scroll.loose > table.tableblock :not(pre):not([class^=L]) > code, +#content .table-scroll.loose > table.tableblock code.words > span { + white-space: normal; overflow-wrap: break-word; } +#content .table-scroll.loose > table.tableblock code span.wbr { display: inline; } +/* A word a phone keeps whole, code.whole (postprocess.mjs), stays on one line at every width. */ #content code.whole, #content code.words > span.whole { white-space: nowrap; } /* Inline code of the role keep, such as a target or a file a reader copies, stays on one line at every width, in a table too: postprocess.mjs marks no part in it. */ #content code.keep { white-space: nowrap; } /* A table of the role key-column keeps room for a few words a line in its first column, the one a reader starts from: without it, at 1199px, "I need to" of crypto's decision table is three - words wide, its other columns as wide as their names. Where the table does not fit with that - room and its names whole, its box marked parts, the names of its other columns break between - their parts, short names too, where postprocess.mjs marks them in such a table, but those of - the role keep. */ + words wide, its other columns as wide as their names. Its names break after their :: and a + path's / where it does not fit with them whole, and never between their other parts: where + it does not fit even so, it stacks (the script below). A hyphenated word of its first + column, `password-reset`, stays whole, as a matrix's key does (below). */ table.tableblock.key-column > tbody > tr > td:first-child { min-width: 10em; } -#content .table-scroll.parts > table.key-column code.whole, -#content .table-scroll.parts > table.key-column code.words > span.whole { white-space: normal; } +/* The first column of a matrix (postprocess.mjs), the key a reader finds a row by, such as a + profile `native-single-on-native` or a dataset `1,000 members, 15-character keys`, keeps each + of its words whole and room for a few of them a line: a row is then one line or two, not one + line a part, and the matrix scrolls in its box. */ +table.tableblock.matrix span.key, table.tableblock.key-column span.key { white-space: nowrap; } +table.tableblock.matrix > tbody > tr > td:first-child { min-width: 9em; } /* A word of code longer than any line from 600px holds, code.long (postprocess.mjs), such as a linker's symbol, breaks between its parts at every width: kept whole, it would make the page - wider than the screen. */ + wider than the screen. In a table it breaks as the table's box allows, as any name there. */ #content code.long, #content code.words > span.long { white-space: normal; } @media screen and (min-width: 37.5em) { #content code.long span.wbr, #content code.words > span.long span.wbr { display: inline; } @@ -190,9 +198,10 @@ between their parts stacks its rows as a phone's do: the script below marks its box stacked, since only a measure tells whether a table fits. A table that fits is laid out as a table; without the script, one that does not scrolls in its box. A matrix, a table of eight columns - or more, such as a benchmark's or a profile's, is read down its columns as much as along its - rows: stacked, each row would be a card of eight lines or more and its columns could no - longer be compared, so wider than a phone it stays a table and scrolls in its box. */ + or more such as a benchmark's or a profile's, which postprocess.mjs marks, is read down its + columns as much as along its rows: stacked, each row would be a card of eight lines or more + and its columns could no longer be compared, so wider than a phone it stays a table and + scrolls in its box. */ .table-scroll.stacked > table.tableblock, .table-scroll.stacked > table.tableblock > tbody, .table-scroll.stacked > table.tableblock > tbody > tr, .table-scroll.stacked > table.tableblock > tbody > tr > td, @@ -212,29 +221,40 @@ } diff --git a/tools/doc/extensions_test.py b/tools/doc/extensions_test.py index dec3288a..dd557326 100755 --- a/tools/doc/extensions_test.py +++ b/tools/doc/extensions_test.py @@ -43,6 +43,8 @@ # breaks the line as would and is never copied (postprocess.mjs). SCOPE = '' PART = '' +# The break after a / of a path, a part too, which a table breaks at as it does after a ::. +PATH = '' def installed() -> None: @@ -163,28 +165,31 @@ def test_short_inline_code_stays_whole(_: None) -> None: html = body(convert(f'Read `#xactor-invariant-13`, `{long}`, `{angles}`,\n' f'`one {long}` and link:#x[`linked-name`].\n')) assert '#xactor-invariant-13' in html, html - assert f'{long}' in html, html + broken = parts('webcpp-|xactor-|invariant-|36') + assert f'{broken}' in html, html assert f'{angles}' in html, html - assert (f'one {long}' + assert (f'one {broken}' in html), html assert 'linked-name' in html, html def test_a_flag_keeps_its_leading_hyphen(_: None) -> None: - # A word too long for a phone's line may break at one of its hyphens, but never right after - # the hyphens that open a flag, which would end a line with them alone, read as a dash: they - # stay with the flag's first character, which the style keeps on one line. A hyphen inside a - # word, and a word short enough to stay whole, are left as they were. + # A word too long for a phone's line may break after one of its hyphens, a part of its name, + # but never right after the hyphens that open a flag, which would end a line with them alone, + # read as a dash: they stay with the flag's first character, which the style keeps on one + # line. A word short enough to stay whole is left as it was. html = body(convert('Link with `-mexec-model=reactor`, compile with ' '`-mllvm -wasm-use-legacy-eh=false`, give `--a-flag-wider-than-a-line`, ' 'but `-short` and `a-name-with-hyphens-past-24` stay as they are.\n')) - assert '<linkflags>-mexec-model=reactor' in html, ( - html) - assert ('-mllvm ' - '-wasm-use-legacy-eh=false' in html), html - assert '--a-flag-wider-than-a-line' in html, html + assert parts('<linkflags>-mexec-|model=reactor') \ + in html, html + assert parts('-mllvm ' + '-wasm-|use-|legacy-|eh=false') \ + in html, html + flag = parts('--a-|flag-|wider-|than-|a-|line') + assert flag in html, html assert '-short' in html, html - assert 'a-name-with-hyphens-past-24' in html, html + assert parts('a-|name-|with-|hyphens-|past-|24') in html, html lead = [(media, declarations) for media, selectors, declarations in page_style() for selector in selectors if selector.endswith('.lead')] assert lead == [(None, {'white-space': 'nowrap'})], lead @@ -268,8 +273,9 @@ def test_urls_in_code_stay_as_written_when_escaped(_: None) -> None: def parts(html: str) -> str: """The html with each | written as the break between two parts of a name that only a phone's - style keeps, and each as the break after a ::, which every style keeps.""" - return html.replace('', SCOPE).replace('|', PART) + style keeps, a path's after its /, and each as the break after a ::, which every style + keeps.""" + return html.replace('', SCOPE).replace('/|', '/' + PATH).replace('|', PART) def test_reference_headings_break_after_scopes(_: None) -> None: @@ -284,9 +290,9 @@ def test_reference_headings_break_after_scopes(_: None) -> None: def test_long_names_break_between_their_parts(_: None) -> None: # A name of code too long for a phone's line may break after a ::, a _, a / or a . between - # letters, before the ( or the < that ends a name, and between the words of a name in camel - # case, never between two letters of a word; prose, a listing, an attribute and a word short - # enough to stay whole are left as they are. + # letters, after a - inside a word, before the ( or the < that ends a name, and between the + # words of a name in camel case, never between two letters of a word; prose, a listing, an + # attribute and a word short enough to stay whole are left as they are. name = 'a_very_long_snake_case_name' broken = parts('a_|very_|long_|snake_|case_|name') header = 'webcpp/demo/long_header_name.hpp' @@ -310,7 +316,7 @@ def test_long_names_break_between_their_parts(_: None) -> None: for code in (f'{broken}{PART}(value)', parts(f'webcpp::demo::{broken}'), parts('std::optional|<boost::json::value>'), - parts('libs/|xstate/|test/|oracle//|update-expected'), + parts('libs/|xstate/|test/|oracle//|update-|expected'), parts('xstate.|done.|state.|coffee.|preparation'), 'short_name', parts('get_|initial_|microsteps|(machine, ' @@ -596,14 +602,16 @@ def test_style_breaks_a_word_only_when_it_must(_: None) -> None: def test_style_keeps_part_breaks_to_a_phone(_: None) -> None: # From 600px a break between two parts of a name is no box, in a heading, a URL and inline # code alike, and below it every break is live; a break after a :: of a heading is live at - # every width. + # every width. In a table, a break of code is live only where the table's box says so (the + # page's script), at every width. hidden = [(media, selector) for media, selectors, declarations in page_style() if declarations.get('display') == 'none' for selector in selectors if 'wbr' in selector] - assert sorted(hidden) == sorted([ + assert sorted(hidden, key=str) == sorted([ ('screen and (min-width: 37.5em)', 'span.wbr.part'), ('screen and (min-width: 37.5em)', '#content :not(pre):not([class^=L])>code span.wbr'), - ]), hidden + (None, '#content table.tableblock code span.wbr'), + ], key=str), hidden def test_breaks_are_never_wbr_and_never_copied(_: None) -> None: @@ -703,31 +711,79 @@ def test_a_word_longer_than_any_line_breaks_at_every_width(_: None) -> None: ], key=str), rules -def test_style_breaks_names_in_a_table_between_their_parts(_: None) -> None: - # A table too wide for its box with its names whole, which the page's script marks parts, - # and a table of the role wrap-names at every width, wrap their inline code and keep its part - # breaks, so that a column is as narrow as the longest part of its names: a table of long - # names fits its page instead of scrolling. A table that fits keeps its names whole, as it - # did before the script, from 600px. A word a phone keeps whole stays whole. +def test_style_breaks_names_in_a_table_in_steps(_: None) -> None: + # In a table, inline code stays on one line between the breaks postprocess.mjs marks, at + # every width: never at a _ or a - by itself, as CSS would wrap it. A table that fits keeps + # its names whole. One too wide for its box with them whole, which the page's script marks + # names, breaks them only after a :: and a path's /, and between two names; one too wide even + # so, marked parts, between their other parts too: a column then as narrow as the longest + # part of its names. A table of the role wrap-names keeps its breaks after a :: and a / live + # at every width. A table laid out as stacked rows and still too wide, marked loose, lets its + # code wrap where it must. rules = {(media, selector): declarations for media, selectors, declarations in page_style() for selector in selectors} - wrapping = {'white-space': 'normal', 'overflow-wrap': 'break-word'} - for media, scope in (('screen and (max-width: 74.9375em)', 'table.tableblock'), - (None, '.table-scroll.parts>table.tableblock'), - (None, 'table.tableblock.wrap-names')): - for selector in (f'{scope} :not(pre):not([class^=L])>code', f'{scope} code.words>span'): - assert rules.get((media, selector)) == wrapping, (media, selector) + table = '#content table.tableblock' + for selector in (f'{table} :not(pre):not([class^=L])>code', f'{table} code.words>span'): + assert rules.get((None, selector)) == {'white-space': 'nowrap'}, selector + assert rules.get((None, f'{table} :not(pre):not([class^=L])>code.words')) == \ + {'white-space': 'normal'}, rules + assert rules.get((None, f'{table} code span.wbr')) == \ + {'display': 'none', 'white-space': 'normal'}, rules live = {selector for (media, selector), declarations in rules.items() - if declarations == {'display': 'inline'} and 'wbr' in selector - and media == 'screen and (min-width: 37.5em)' and 'long' not in selector} - assert live == {'#content .table-scroll.parts>table.tableblock code span.wbr', - '#content table.tableblock.wrap-names code span.wbr'}, live + if declarations == {'display': 'inline'} and 'wbr' in selector and media is None} + assert live == { + '#content .table-scroll.names>table.tableblock code span.wbr:not(.part)', + '#content .table-scroll.names>table.tableblock code span.wbr.path', + '#content table.tableblock.wrap-names code span.wbr:not(.part)', + '#content table.tableblock.wrap-names code span.wbr.path', + '#content .table-scroll.parts>table.tableblock code span.wbr', + '#content .table-scroll.loose>table.tableblock code span.wbr', + }, live + loose = {'white-space': 'normal', 'overflow-wrap': 'break-word'} + for selector in ('#content .table-scroll.loose>table.tableblock ' + ':not(pre):not([class^=L])>code', + '#content .table-scroll.loose>table.tableblock code.words>span'): + assert rules.get((None, selector)) == loose, selector + # No rule of a width wraps a table's code as prose any more. + wrapping = [(media, selector) for (media, selector), declarations in rules.items() + if 'table' in selector and 'code' in selector and 'loose' not in selector + and declarations.get('white-space') == 'normal' and 'words' not in selector + and 'wbr' not in selector] + assert wrapping == [], wrapping assert rules.get((None, '#content code.whole')) == {'white-space': 'nowrap'}, rules html = body(convert('[.wrap-names,cols="1,1,1",options="header"]\n|===\n| A | B | C\n\n' '| x | y | z\n|===\n')) assert '' in html, html +def test_a_matrix_keeps_its_keys_whole(_: None) -> None: + # A table of eight columns or more is a matrix, read down its columns as much as along its + # rows: postprocess.mjs marks it, the page's script lets it scroll rather than stack, and + # each word of its first column with a hyphen inside, a profile such as + # native-single-on-native, is a key the style keeps on one line, so that a row is one line or + # two rather than one a part. Code, the header and the other columns are left as they are. + def source(columns: int) -> str: + header = ' '.join(f'| H{index}' for index in range(columns)) + row = '| native-single-on-native, 15-character keys | `a-code-name-longer-than-24` ' + \ + ' '.join(f'| x-{index}' for index in range(columns - 2)) + return (f'[cols="{",".join(["1"] * columns)}",options="header"]\n|===\n{header}\n\n' + f'{row}\n|===\n') + html = body(convert(source(8) + '\n' + source(7))) + matrix, plain = html.split('
')[:2] + assert '' in matrix, matrix + assert ('native-single-on-native, ' + '15-character keys

') in matrix, matrix + assert parts('a-|code-|name-|longer-|than-|24') in matrix, matrix + assert '>x-0

' in matrix and 'x-' not in matrix, matrix + assert 'matrix' not in plain and 'class="key"' not in plain, plain + rules = {selector: declarations for media, selectors, declarations in page_style() + if media is None for selector in selectors} + for selector in ('table.tableblock.matrix span.key', 'table.tableblock.key-column span.key'): + assert rules.get(selector) == {'white-space': 'nowrap'}, (selector, rules) + assert rules.get('table.tableblock.matrix>tbody>tr>td:first-child') == \ + {'min-width': '9em'}, rules + + def test_style_lifts_a_link_s_underline_off_underscores(_: None) -> None: # A link's underline at its default height covers the underscores of a name of code, which # then reads as words: under a link that holds code, or in code that holds a link, it is @@ -746,17 +802,24 @@ def test_a_table_too_wide_stacks_as_on_a_phone(_: None) -> None: script = re.search(r'', docinfo, flags=re.S) assert script, docinfo for part in ("querySelectorAll('div.table-scroll')", - 'box.scrollWidth > box.clientWidth', "classList.add('stacked')", - "addEventListener('DOMContentLoaded', stack)", - "addEventListener('resize', stack)", + 'box.scrollWidth > box.clientWidth', 'box.classList.add(step)', + "addEventListener('DOMContentLoaded', fit)", + "addEventListener('resize', fit)", # The web fonts and images change the widths without a resize. - "addEventListener('load', stack)", 'document.fonts?.ready.then(stack)', - # A table breaks its names between their parts before it stacks, and only - # when it does not fit with them whole. - "classList.remove('parts', 'stacked')", "classList.add('parts')", - # A matrix, of eight columns or more, scrolls in its box rather than stack. - 'const MATRIX = 8;', "':scope > table > colgroup > col'", - 'columns(box) < MATRIX && wide(box)'): + "addEventListener('load', fit)", 'document.fonts?.ready.then(fit)', + # A table breaks its names after their :: and then between their parts + # before it stacks, and only when it does not fit with them whole; stacked + # and still too wide, its code wraps where it must. + "const STEPS = ['names', 'parts', 'stacked', 'loose'];", + 'classList.remove(...STEPS)', "mark(boxes.filter(wide), 'names')", + "mark(named.filter((box) => !keyed(box)), 'parts')", + # A table of the role key-column stacks rather than break its names between + # their parts. + "classList.contains('key-column')", + # A matrix (postprocess.mjs) scrolls in its box rather than stack. + "classList.contains('matrix')", + "mark(parted.filter((box) => !matrix(box)), 'stacked')", + "'loose'"): assert part in script.group(1), (part, script.group(1)) phone = {} for media, selectors, declarations in page_style(): @@ -773,8 +836,9 @@ def test_a_table_too_wide_stacks_as_on_a_phone(_: None) -> None: def test_a_key_column_keeps_room_for_its_words(_: None) -> None: # A table of the role key-column keeps room in its first column, at every width, for the # words a reader starts from: crypto's decision table. Its other columns' names, short ones - # too, which stay whole elsewhere, break between their parts where it does not fit - # otherwise (the page's script marks its box parts) to make that room. + # too, which stay whole elsewhere, break after their :: and their path's /, then between + # their other parts, where it does not fit otherwise (the page's script marks its box) to + # make that room. rules = {selector: declarations for media, selectors, declarations in page_style() if media is None for selector in selectors} assert rules.get('table.tableblock.key-column>tbody>tr>td:first-child') == \ @@ -786,19 +850,18 @@ def test_a_key_column_keeps_room_for_its_words(_: None) -> None: '[#x]\n== X\n')) assert '/third_party//ctaes' in kept, kept assert 'a_b.cpp' in kept, kept - for selector in ('#content .table-scroll.parts>table.key-column code.whole', - '#content .table-scroll.parts>table.key-column code.words>span.whole'): - assert rules.get(selector) == {'white-space': 'normal'}, (selector, rules) - source = ('|===\n| A | B | C\n\n| a | `+/third_party//ctaes+` ' + source = ('|===\n| A | B | C\n\n| a password-reset link | `+/third_party//ctaes+` ' '| `+x+` and `+aes256+`\n|===\n') html = body(convert('[.wrap-names.key-column,cols="1,1,1",options="header"]\n' + source + '\n[cols="1,1,1",options="header"]\n' + source)) keyed, plain = html.split('
')[:2] assert 'class="tableblock frame-all grid-all stretch wrap-names key-column"' in keyed, keyed - part = '' - assert f'/third_{part}party//{part}ctaes' in keyed, keyed - assert f'aes256{part}<backends::ctaes>' \ - '' in keyed, keyed + # A hyphenated word of its first column stays whole, as a matrix's key does. + assert '

a password-reset link

' in keyed, \ + keyed + assert 'class="key"' not in plain, plain + assert parts('/third_|party//|ctaes') in keyed, keyed + assert parts('aes256|<backends::ctaes>') in keyed, keyed assert 'x' in keyed, keyed assert '/third_party//ctaes' in plain, plain assert 'aes256<backends::ctaes>' in plain, plain @@ -861,7 +924,8 @@ def test_detail_macros_stay_out_of_the_reference(_: None) -> None: test_style_scrolls_a_wide_table_in_its_box, test_style_gives_the_content_a_right_gutter_from_the_toc, test_a_word_longer_than_any_line_breaks_at_every_width, - test_style_breaks_names_in_a_table_between_their_parts, + test_style_breaks_names_in_a_table_in_steps, + test_a_matrix_keeps_its_keys_whole, test_style_lifts_a_link_s_underline_off_underscores, test_a_table_too_wide_stacks_as_on_a_phone, test_a_key_column_keeps_room_for_its_words, diff --git a/tools/doc/postprocess.mjs b/tools/doc/postprocess.mjs index 4fc2beaf..ee3c404d 100644 --- a/tools/doc/postprocess.mjs +++ b/tools/doc/postprocess.mjs @@ -39,11 +39,16 @@ // with its names whole, so that the table's first column keeps room for its // words. // +// A table of eight columns or more, a matrix, is marked `matrix`, and each +// hyphenated word of its first column, and of a key-column table's, `key`, +// which the style keeps whole. +// // A name too long for a phone's line, in inline code, in a heading of the // reference (and its entry in the table of contents, after a `::` only), `webcpp::xactor::scheduler::run_one`, or in a bare URL, may break // between its parts, which an empty `` marks: after a `::`, // a `_`, a `/`, or a `.` between letters, before the `(` or the `<` that ends -// a name, and in code between the words of a name in camel case. So a phone +// a name, and in code after a `-` inside a word and between the words of a +// name in camel case. So a phone // breaks it there and never between two letters of a word, which the style // allows only to a part still wider than the line. From 600px, where such a // name has room, only the break after a `::` of a heading stays, as the @@ -122,9 +127,12 @@ const LONG = 60; // A break after a `::`, which a heading of the reference keeps at every width; // and one between the other parts of a name, which the style keeps only on a -// phone: from 600px every such name has room on a line. +// phone: from 600px every such name has room on a line. The break after a `/` +// of a path is such a part, which a table too wide for its box breaks at as it +// does after a `::` (docinfo.html). const SCOPE = ''; const PART = ''; +const PATH = ''; // The points a name breaks at, in text that holds no markup and its // references, each with what it becomes: after each `::`; after a run of `_` @@ -134,20 +142,22 @@ const PART = ''; const BREAKS = [ [/::/g, (scope) => scope + SCOPE], [/(?<=[A-Za-z0-9])_+(?=[A-Za-z0-9])/g, (run) => run + PART], - [/(?<=[^\s/])\/+(?=[^\s/])/g, (run) => run + PART], + [/(?<=[^\s/])\/+(?=[^\s/])/g, (run) => run + PATH], [/(?<=[A-Za-z])\.(?=[A-Za-z])/g, (dot) => dot + PART], [/(?<=\w)(?=\(|<)/g, () => PART] ]; -// Code breaks at these too, and between the words of a name written in camel -// case, `resolveHistory` and `DefaultTransition`: never prose, whose JavaScript -// is one word. And the hyphens that open a flag, `-mexec-model=reactor` or +// Code breaks at these too, after a `-` inside a word, `websocket-client-async`, +// and between the words of a name written in camel case, `resolveHistory` and +// `DefaultTransition`: never prose, whose JavaScript is one word and whose +// hyphens a line breaks after anyway. And the hyphens that open a flag, `-mexec-model=reactor` or // `--target`, at the start of a word or after a space, a `=`, a `(`, a `,` or // the `;` of a reference such as `>`, stay with the flag's first character // in a span the style keeps on one line: a break right after them would end a // line with a hyphen alone, which reads as a dash. const CODE_BREAKS = [ ...BREAKS, + [/(?<=[A-Za-z0-9])-(?=[A-Za-z0-9])/g, (hyphen) => hyphen + PART], [/(?<=[a-z])(?=[A-Z])/g, () => PART], [/(?<=^|[\s=(,;])-+[A-Za-z0-9]/g, (flag) => `${flag}`] ]; @@ -233,6 +243,45 @@ function partsOfKeyColumnTables(html) { ); } +// A table of MATRIX columns or more, a matrix, such as a benchmark's or a +// profile's, read down its columns as much as along its rows: its table is +// marked `matrix`, which the page's script lets scroll in its box rather than +// stack (docinfo.html), and each word of its first column's text with a hyphen +// inside, a key such as `native-single-on-native`, is marked `key`, which the +// style keeps on one line; and so is each of the first column of a table of the +// role key-column, `password-reset`. +const MATRIX = 8; +const FIRST_CELL = /(\s*]*>)([\s\S]*?)(<\/td>)/g; +const HYPHENATED = /[^\s<>]*[A-Za-z0-9]-[A-Za-z0-9][^\s<>]*/g; + +// The html of a cell with each hyphenated word of its text, outside its code, +// marked a key. +function keysOf(html) { + let code = false; + return html + .split(/(<[^>]+>)/) + .map((part, index) => { + if (index % 2 === 1) { + code = /^/.test(part)); + return part; + } + return code ? part : part.replace(HYPHENATED, (word) => `${word}`); + }) + .join(''); +} + +function matrices(html) { + return html.replace(TABLE, (table) => { + const matrix = (table.match(/= MATRIX; + if (!matrix && !/^]*\sclass="[^"]*\bkey-column\b/.test(table)) { + return table; + } + const marked = matrix ? table.replace(/^(]*\sclass="[^"]*)"/, '$1 matrix"') : table; + return marked.replace(BODY, (body) => + body.replace(FIRST_CELL, (_cell, open, text, close) => open + keysOf(text) + close)); + }); +} + // A bare URL, which Asciidoctor writes as the text of its link, and which holds // no break yet: one in a heading has its breaks already. const BARE_URL = /()([^<]*)(<\/a>)/g; @@ -450,7 +499,9 @@ function curledApostrophes(html) { class Page extends Postprocessor { process(_document, output) { - const page = labelledTables(partsOfKeyColumnTables(wordsOfCode(decodeEntities(output)))); + const page = labelledTables( + matrices(partsOfKeyColumnTables(wordsOfCode(decodeEntities(output)))) + ); const built = curledApostrophes( boxedTables(partsOfURLs(scopesOfContents(partsOfHeadings(page)))) ); From a249be4023c0c5bb78f26eba0c65ec01a5dbfb6b Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 20:52:35 -0300 Subject: [PATCH 55/59] tools/same_program: the compare rule finds each side of the pair by its directory between either separator, as b2 spells a path on Windows with backslashes, where it compared nothing and failed every pair --- doc/releases/0.1.0.adoc | 1 + tools/same_program/same_program.jam | 25 +++++++++++++++++++------ tools/test/webcpp_jam_test.py | 27 +++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 484472e6..21354830 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -256,6 +256,7 @@ Emscripten's notice that the runtime is kept alive. code. * Added the lint rule canary pins, which checks crypto's canaries against their submodules. * Added webcpp.same-program, which proves a library named and not called adds no byte. +* Fixed webcpp.same-program comparing nothing on Windows, whose paths b2 spells with backslashes. * Added the lint rule entropy sources, which refuses a weaker source in a header that reads entropy. * Fixed webcpp.compile-diagnostic passing on a directive clang's -verify diff --git a/tools/same_program/same_program.jam b/tools/same_program/same_program.jam index 7184309e..c62d2870 100644 --- a/tools/same_program/same_program.jam +++ b/tools/same_program/same_program.jam @@ -78,6 +78,22 @@ rule same-program ( found + : name : sources + : library : only * : requirements : $(only) $(name) : $(name) ; } +# The side of the pair named name that the target source belongs to, with or +# without, from the directory of that side in its path, which b2 spells with +# the platform's separator, a backslash on Windows; nothing for another +# directory. +rule side ( name : source ) +{ + if [ MATCH "[/\\]($(name)_with)[/\\]" : $(source) ] + { + return with ; + } + else if [ MATCH "[/\\]($(name)_without)[/\\]" : $(source) ] + { + return without ; + } +} + # The two programs are the sources whose name is the pair's, in the directory # of their side, never the first and the second source: a link may add files # (MSVC's .pdb) or order them as it likes. @@ -88,13 +104,10 @@ rule compare ( target : sources * : properties * ) { if $(source:B) = $(name) && ! ( $(source:S) = .pdb ) { - if [ MATCH "/($(name)_with)/" : $(source) ] - { - WITH on $(target) = $(source) ; - } - else if [ MATCH "/($(name)_without)/" : $(source) ] + switch [ side $(name) : $(source) ] { - WITHOUT on $(target) = $(source) ; + case with : WITH on $(target) = $(source) ; + case without : WITHOUT on $(target) = $(source) ; } } } diff --git a/tools/test/webcpp_jam_test.py b/tools/test/webcpp_jam_test.py index 469f3e50..4c632d5b 100755 --- a/tools/test/webcpp_jam_test.py +++ b/tools/test/webcpp_jam_test.py @@ -1360,6 +1360,32 @@ def test_a_library_with_gc_flags_still_compares_equal(root): assert passed(result) == {'hello_unused'}, (request, passed(result), result.stdout[-4000:]) +def test_the_pair_is_found_by_its_directory_on_every_path_separator(root): + # The compare rule tells the two programs apart by the directory of their side, which b2 + # spells with the platform's separator: a backslash on Windows, where the pair was compared + # with nothing until the rule read both separators. b2 here runs on POSIX, so the rule is fed + # the targets' names as each platform spells them (a Jam token's backslash is doubled). + sources = { + 'posix with': 'hello_unused.exe', + 'posix without': 'hello_unused.exe', + 'nt with': r'hello_unused.exe', + 'nt without': r'hello_unused.exe', + 'neither': r'hello_unused.exe', + 'a prefix only': 'hello_unused.exe', + } + jamfile = 'import modules ;\nimport webcpp ;\n\n' + for label, source in sources.items(): + jamfile += (f'ECHO "side {label}:" ' + f'[ modules.call-in webcpp-same-program : side hello_unused : {source} ] ;\n') + harness.add_library(root, 'probe', jamfile, {}) + result = harness.run_b2(root, 'libs/probe/test') + harness.expect(result, True) + found = {line.split(':', 1)[0].removeprefix('side '): line.split(':', 1)[1].strip() + for line in result.stdout.splitlines() if line.startswith('side ')} + assert found == {'posix with': 'with', 'posix without': 'without', 'nt with': 'with', + 'nt without': 'without', 'neither': '', 'a prefix only': ''}, found + + CASES = [ test_link_fail_checks_linking_and_keeps_success_controls, test_source_only_corpus_is_not_loaded_as_a_build, @@ -1404,6 +1430,7 @@ def test_a_library_with_gc_flags_still_compares_equal(root): test_the_pair_shares_one_name, test_the_pair_shares_one_name_on_emscripten, test_a_library_with_gc_flags_still_compares_equal, + test_the_pair_is_found_by_its_directory_on_every_path_separator, test_a_pair_built_without_exceptions_links_the_handler_and_compares_equal, test_a_shared_library_is_compared_as_a_static_one, ] From c953b5ae29e58758b95f4ee8c6253b9ed67601d4 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 20:52:35 -0300 Subject: [PATCH 56/59] tools/report: a failed link that b2 records under the .pdb MSVC writes beside the program is the program's, not a failure outside every test: a link-fail test's expected failure on MSVC --- doc/releases/0.1.0.adoc | 1 + tools/report/lanes.py | 4 ++ tools/report/report_test.py | 81 ++++++++++++++++++++++++++++++++++++- 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 21354830..9237f351 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -257,6 +257,7 @@ code. * Added the lint rule canary pins, which checks crypto's canaries against their submodules. * Added webcpp.same-program, which proves a library named and not called adds no byte. * Fixed webcpp.same-program comparing nothing on Windows, whose paths b2 spells with backslashes. +* Fixed the report counting outside every test a failed MSVC link that b2 records under the .pdb. * Added the lint rule entropy sources, which refuses a weaker source in a header that reads entropy. * Fixed webcpp.compile-diagnostic passing on a directive clang's -verify diff --git a/tools/report/lanes.py b/tools/report/lanes.py index 6c462691..94b2b062 100644 --- a/tools/report/lanes.py +++ b/tools/report/lanes.py @@ -401,6 +401,10 @@ def row(location: str, example: bool, row_name: str, row_type: str) -> tuple[Row action = Action(text_of(element, 'name'), status, slashed(text_of(element, 'path')), command, text_of(element, 'output')) builds = owners.get(action.path, []) + # MSVC's link writes the program and its .pdb, and b2 may record the link under the .pdb, + # which no test needs: it is the link of the program beside it. + if not builds and action.path.endswith('.pdb'): + builds = owners.get(action.path[:-len('.pdb')] + '.exe', []) for build in builds: build.actions.append(action) if not builds and action.status != 0: diff --git a/tools/report/report_test.py b/tools/report/report_test.py index 7262a89f..5d9e4e61 100644 --- a/tools/report/report_test.py +++ b/tools/report/report_test.py @@ -15,7 +15,8 @@ whose transcript differs, a run failure, and a library's own lane on a target, named after the target and the library, which its column and its failures show and which it must hold true; an emscripten lane, its link-only program a link test, and a driven test whose driver fails, a run -failure. One case uses lanes.py and pages.py alone; one checks that no sample names the machine's +failure. One case uses lanes.py and pages.py alone, and one reads a link that MSVC's lane records +under the program's .pdb; one checks that no sample names the machine's temporary directory, and one that none holds what Emscripten says of its cache; a last one records every sample afresh, untrimmed, and checks that the report reads it as it reads the committed one. Every page written is checked to be self-contained, to link only to the report's own pages, to the @@ -824,6 +825,83 @@ def test_lanes_and_pages_work_alone(root: Path) -> None: check_pages(root / 'pages') +# What b2 writes on Windows for a test of webcpp.link-fail whose link fails as expected, trimmed to +# what lanes.py reads: MSVC's link builds the program and its .pdb, and b2 records the failed link +# under the .pdb, a target the test does not list as needed. A program of the build's tools, which +# no test owns, fails its link too, outside every test. No sample can be recorded on macOS. +MSVC_LINK_FAIL = r""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" + + +def test_a_failed_link_msvc_records_under_its_pdb_is_the_programs(root: Path) -> None: + # The link of a link-fail test is its program's, though b2 names it by the .pdb beside the + # .exe: the test passes and nothing of it is outside every test. A .pdb whose program no test + # owns stays outside. + path = root / 'msvc-link-fail.xml' + path.write_text(MSVC_LINK_FAIL) + lane = lanes.read_lane('native', path) + assert lane.toolset == 'msvc-14.3', lane.toolset + assert {row_id: row.verdict() for row_id, row in lane.rows.items()} == { + 'demo/absent': 'pass'}, lane.rows + build = lane.rows['demo/absent'].builds[0] + assert [action.path.rsplit('/', 1)[-1] for action in build.actions] == [ + 'absent.obj', 'absent.pdb', 'absent.test'], build.actions + assert [action.path for action in lane.outside] == [ + 'W:/build/bin/tools/msvc-14.3/dbg/helper.pdb'], lane.outside + + def tables(out: Path) -> dict[str, list[list[list[tuple[str, frozenset[str], str | None]]]]]: """The tables of the pages directly in out, by page, a lane's header by its lane: the toolset under it is the machine's (clang-darwin-21 here, clang-linux-22 on a Linux runner).""" @@ -911,6 +989,7 @@ def test_samples_read_as_b2_writes_them_today(root: Path) -> None: test_served_test_passes_and_fails_as_a_run, test_emscripten_lane_and_its_link_and_driven_tests, test_lanes_and_pages_work_alone, + test_a_failed_link_msvc_records_under_its_pdb_is_the_programs, test_samples_name_no_temporary_directory, test_samples_hold_nothing_of_emscriptens_cache, test_samples_read_as_b2_writes_them_today, From 5a83699f704349a2f2110efba079a7fa9baecaee Mon Sep 17 00:00:00 2001 From: R Date: Mon, 16 Nov 2026 04:44:39 -0300 Subject: [PATCH 57/59] libs/crypto: webcpp::crypto as a submodule, at its pull request's head The library's repository is webcpporg/crypto. The third-party targets compile its canaries, so the submodule lands with them in one pull request. The recorded commit becomes the library's main by a fast-forward once this merges. --- .gitmodules | 3 +++ libs/crypto | 1 + 2 files changed, 4 insertions(+) create mode 160000 libs/crypto diff --git a/.gitmodules b/.gitmodules index 92a151ce..20c0dc58 100644 --- a/.gitmodules +++ b/.gitmodules @@ -67,3 +67,6 @@ path = third_party/libs/bips url = https://github.com/bitcoin/bips.git shallow = true +[submodule "libs/crypto"] + path = libs/crypto + url = ../crypto.git diff --git a/libs/crypto b/libs/crypto new file mode 160000 index 00000000..b7c97734 --- /dev/null +++ b/libs/crypto @@ -0,0 +1 @@ +Subproject commit b7c97734d879595bfc9d0c1addb675d2750abc5f From 98cd18d7e22a47473fdd51618ad6262afd99f1c8 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 16 Nov 2026 07:58:41 -0300 Subject: [PATCH 58/59] libs/crypto: the page's title within the site's 60 characters, and the counting header's misc-definitions-in-headers exception that Linux's clang-tidy asks --- libs/crypto | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/crypto b/libs/crypto index b7c97734..d242be80 160000 --- a/libs/crypto +++ b/libs/crypto @@ -1 +1 @@ -Subproject commit b7c97734d879595bfc9d0c1addb675d2750abc5f +Subproject commit d242be8022018b89ebd70f754eef17244f572c1c From 73c88736d78f65ec4be1365728af2dcc5b63f7be Mon Sep 17 00:00:00 2001 From: R Date: Mon, 16 Nov 2026 10:31:05 -0300 Subject: [PATCH 59/59] tools/doc: a table with a header column gives its header cells their scope, the head's col and the body's row, as html-validate's wcag/h63 asks of webcpp::crypto's namespace tables --- doc/releases/0.1.0.adoc | 1 + tools/doc/extensions_test.py | 21 +++++++++++++++++++++ tools/doc/postprocess.mjs | 25 +++++++++++++++++++++++-- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 9237f351..240668dc 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -82,6 +82,7 @@ None. * Fixed a matrix's or a key-column table's first column breaking a hyphenated key, such as a profile's name, into a line per part. * Added the changelog rule's refusal of inline anchors, which hid a {cpp} attribute from its line. * Fixed links over code hiding the underscores of names under their underline. +* Fixed the header cells of a table with a header column lacking their scope, which the site's HTML check refuses. * Changed the references to leave out detail macros, WEBCPP_*_DETAIL_*. * Fixed the WASIp2 test launcher interrupting large finite workloads after 60 seconds. * Fixed Chrome provisioning and browser/TLS profile coverage in Asio CI lanes. diff --git a/tools/doc/extensions_test.py b/tools/doc/extensions_test.py index dd557326..fb22b588 100755 --- a/tools/doc/extensions_test.py +++ b/tools/doc/extensions_test.py @@ -212,6 +212,26 @@ def test_wide_table_labels_its_cells(_: None) -> None: assert 'data-label' not in tables[1], tables[1] +def test_a_header_column_scopes_its_header_cells(_: None) -> None: + # A table whose first column is a header column (cols="1h,...") has header cells in its body + # too, so each header cell says what it heads, as WCAG's technique H63 asks: the head's its + # column, the body's its row. A table without a header column is left as it was. + html = body(convert('[cols="1h,2,2",options="header"]\n|===\n| Name | `a` | `b`\n\n' + '| Header\n| ``\n| ``\n\n' + '| Errors\n| none\n| its values\n|===\n\n' + '[cols="1,1,2",options="header"]\n|===\n| Status | Value | What\n\n' + '| `active`\n| 1\n| Its mailbox.\n|===\n')) + tables = re.findall(r'', html, flags=re.S) + assert len(tables) == 2, html + head = ''.join(re.findall(r'.*?', tables[0], flags=re.S)) + rows = ''.join(re.findall(r'.*?', tables[0], flags=re.S)) + assert re.findall(r']*>', head) and all( + ' scope="col"' in cell for cell in re.findall(r']*>', head)), head + assert len(re.findall(r']*>', rows)) == 2 and all( + ' scope="row"' in cell for cell in re.findall(r']*>', rows)), rows + assert 'scope=' not in tables[1], tables[1] + + def test_dashes_stay_as_written_when_escaped(_: None) -> None: # Asciidoctor writes -- as an em dash, in inline code as in prose, which the check of the # rendered page refuses; \-- keeps the two hyphens, and so does a passthrough. @@ -900,6 +920,7 @@ def test_detail_macros_stay_out_of_the_reference(_: None) -> None: test_short_inline_code_stays_whole, test_a_flag_keeps_its_leading_hyphen, test_wide_table_labels_its_cells, + test_a_header_column_scopes_its_header_cells, test_dashes_stay_as_written_when_escaped, test_code_keeps_its_characters_when_escaped, test_urls_in_code_stay_as_written_when_escaped, diff --git a/tools/doc/postprocess.mjs b/tools/doc/postprocess.mjs index ee3c404d..3a462b20 100644 --- a/tools/doc/postprocess.mjs +++ b/tools/doc/postprocess.mjs @@ -31,6 +31,9 @@ // stacks the table's rows; a table of two columns, a name and what it is, // reads stacked without them. // +// A table with a header column gives its header cells their scope: the head's +// `col`, the body's `row`. +// // A word of inline code too long for any line from 600px, more than 60 // characters, is marked `long`, and the style keeps its breaks at every width. // @@ -359,6 +362,24 @@ function labelledTables(html) { }); } +// A table with a header column (cols="1h,...") has header cells in its body as in its head; each +// says what it heads, as WCAG's technique H63 asks and html-validate's wcag/h63 checks: the head's +// its column, the body's its row. A table without one keeps its cells as they are. +const HEAD = /[\s\S]*?<\/thead>/; +const TH = / { + const body = table.match(BODY); + if (body === null || !/ head.replace(TH, ' rows.replace(TH, ']*>|<\/table>/g; @@ -499,8 +520,8 @@ function curledApostrophes(html) { class Page extends Postprocessor { process(_document, output) { - const page = labelledTables( - matrices(partsOfKeyColumnTables(wordsOfCode(decodeEntities(output)))) + const page = scopedHeaders( + labelledTables(matrices(partsOfKeyColumnTables(wordsOfCode(decodeEntities(output))))) ); const built = curledApostrophes( boxedTables(partsOfURLs(scopesOfContents(partsOfHeadings(page))))