From fc2454caa61b00933270483575380512677c515e Mon Sep 17 00:00:00 2001 From: Zhe Feng Date: Sat, 28 Nov 2026 05:49:54 +0000 Subject: [PATCH 1/3] gen_exports: an unfollowed using-directive must be declared (policy skip-directive) collect_injections follows a using-directive only in the ADL-barrier shape; any other directive dropped every name it makes visible without a trace. check_skipped_directives now requires each such directive in a library's own headers to be declared, as a republish or as a skip-directive with its reason, and rejects stale entries. Declared skips are listed in skipped.txt. --- tools/gen_exports.py | 118 ++++++++++++--- .../tests/test_gen_exports_skip_directive.py | 135 ++++++++++++++++++ 2 files changed, 234 insertions(+), 19 deletions(-) create mode 100644 tools/tests/test_gen_exports_skip_directive.py diff --git a/tools/gen_exports.py b/tools/gen_exports.py index 06c38d79..8a529b98 100644 --- a/tools/gen_exports.py +++ b/tools/gen_exports.py @@ -91,6 +91,10 @@ class Policy: namespace another target library owns: re-export every name that library exports directly in through (under `#if ` when given) + [[.skip-directive]] namespace / reason — the library's `using + namespace X;` inside is not a public + spelling; every directive the generator does not + follow must be declared here or as a republish [.deps] add / remove / reason — module edge corrections [.facade] omit-imports / reason — .deps edges src/.cppm cannot `export import` (checked by check_facade) @@ -136,6 +140,9 @@ def extras(self, lib): def republishes(self, lib): return list(self.lib(lib).get("republish", ())) + def skip_directives(self, lib): + return list(self.lib(lib).get("skip-directive", ())) + def deps(self, lib): return self.lib(lib).get("deps", {}) @@ -708,6 +715,28 @@ def _enclosing_ns(m, d): return parts[::-1] +def _directive_scope(m, d): + """(target, enclosing namespace) qualified names of a using-directive + that nominates a boost:: namespace from a named namespace, else None.""" + ns = m.by_id.get(d.target) + if ns is None: + return None + tgt = m.qualified_name(ns) + if not tgt.startswith("boost::"): + return None + parts = _enclosing_ns(m, d) + if not parts: + return None + return tgt, "::".join(parts) + + +def _is_adl_barrier(tgt, prefix): + """The one directive shape collect_injections follows: the target is + nested in the directive's own namespace (`namespace boost { namespace + range_adl_barrier {...} using namespace range_adl_barrier; }`).""" + return tgt.startswith(prefix + "::") + + def _using_target_name(m, d): """(injected qname, target qname) of a namespace-scope using-declaration from the name clang prints as written (`range::count`, @@ -773,24 +802,16 @@ def collect_injections(lib, m, claimed): "file": d.file, "home": lib, "kind": "USING_INJECT", } else: - ns = m.by_id.get(d.target) - if ns is None: - continue - tgt = m.qualified_name(ns) - if not tgt.startswith("boost::"): + scope = _directive_scope(m, d) + if scope is None: continue - parts = _enclosing_ns(m, d) - if not parts: - continue - prefix = "::".join(parts) - if not tgt.startswith(prefix + "::"): - # Only the ADL-barrier shape re-publishes names: a namespace - # nested in the directive's own scope (`namespace boost { - # namespace range_adl_barrier {...} using namespace - # range_adl_barrier; }`). A directive that pulls a sibling - # detail namespace in (`using namespace detail;` inside - # poly_collection::common_impl) is an implementation - # convenience, not a public spelling. + tgt, prefix = scope + if not _is_adl_barrier(tgt, prefix): + # Only the ADL-barrier shape re-publishes names. Any other + # directive (`using namespace detail;` inside + # poly_collection::common_impl) is followed only through a + # policy `republish`; the rest must be declared as + # `skip-directive` (check_skipped_directives). continue directives.append((tgt.split("::"), prefix, d.file)) for tgt_chain, prefix, df in directives: @@ -814,6 +835,62 @@ def collect_injections(lib, m, claimed): return out +def check_skipped_directives(lib, m, policy): + """Policy `skip-directive` entries. collect_injections follows a + using-directive only in the ADL-barrier shape, so a directive in any other + shape drops every name it makes visible (`namespace ublas { namespace + detail { using namespace boost::numeric::ublas; } }` spells all of uBLAS + as ublas::detail::X). Each such directive in the library's own headers + must be declared, either as a `republish` (a public spelling) or as a + `skip-directive` with the reason it is not one, so no spelling is lost + silently. + + Returns (skipped entries, errors): an undeclared directive, a + `skip-directive` that matches none, and one that is also a `republish` + are errors.""" + found = {} + for d in m.indexed(): + if d.kind != "UsingDirectiveDecl" or d.parent is None \ + or d.parent.kind != "NamespaceDecl": + continue + if home_of_file(d.file) not in (lib, "shared"): + continue + scope = _directive_scope(m, d) + if scope is None or _is_adl_barrier(*scope): + continue + tgt, prefix = scope + found.setdefault(prefix, {}).setdefault(tgt, d.file) + republished = {e["namespace"] for e in policy.republishes(lib)} + entries, errors, declared = [], [], set() + for entry in policy.skip_directives(lib): + where = entry["namespace"] + declared.add(where) + entries.append((lib, "skip-directive", where, "", entry["reason"])) + if where in republished: + errors.append("policy skip-directive {}: the namespace is also a " + "republish".format(where)) + elif where not in found: + errors.append( + "policy skip-directive {}: the library's own headers have no " + "using-directive there that the generator does not follow " + "(declare a directive in the library that owns its " + "header)".format(where)) + for prefix, targets in sorted(found.items()): + if prefix in declared or prefix in republished: + continue + for tgt, dfile in sorted(targets.items()): + try: + dfile = Path(dfile).relative_to(bc.ROOT).as_posix() + except (TypeError, ValueError): + pass + errors.append( + "`using namespace {};` in {} ({}) is not followed: declare " + "[[{}.republish]] if {}::X is a public spelling, else " + "[[{}.skip-directive]] with the reason it is not".format( + tgt, prefix, dfile, lib, prefix, lib)) + return entries, errors + + def collect_added(lib, m, policy, claimed): """Policy `add` names: exported like using-injections when the TU declares them (a name the GMF cannot see would not compile).""" @@ -1354,7 +1431,8 @@ def write_meta(out_dir, summary, skipped): encoding="utf-8", newline="\n") lines = [ "# Names the export policy (tools/export_policy.toml) guards, drops or", - "# adds verbatim. GENERATED by tools/gen_exports.py - DO NOT EDIT", + "# adds verbatim, and the using-directives it does not follow.", + "# GENERATED by tools/gen_exports.py - DO NOT EDIT", "# [if ] -- ", "", ] @@ -1726,6 +1804,8 @@ def generate(args, out): added = collect_added(lib, m, policy, inject_view) rp, rp_sources, rp_entries, rp_errors = collect_republished( lib, m, policy, published, upstreams_of(graph, lib), inject_view) + sd_entries, sd_errors = check_skipped_directives(lib, m, policy) + rp_errors += sd_errors if rp_errors: for e in rp_errors: print("error: {}: {}".format(lib, e), file=sys.stderr) @@ -1739,7 +1819,7 @@ def generate(args, out): extra_deps=bc.lib_deps(lib, gfm_final) | {r["owner"] for r in rp.values()}, namespaces=m.namespaces(), published=published[lib]) - sk_entries += rp_entries + sk_entries += rp_entries + sd_entries body = {} if args.no_body_deps else \ collect_body_edges(lib, m, records, claimed) if body: diff --git a/tools/tests/test_gen_exports_skip_directive.py b/tools/tests/test_gen_exports_skip_directive.py new file mode 100644 index 00000000..34fa3add --- /dev/null +++ b/tools/tests/test_gen_exports_skip_directive.py @@ -0,0 +1,135 @@ +"""Every using-directive the generator does not follow must be declared in the +policy: `skip-directive` with a reason, or `republish` +(boost::numeric::ublas::detail -> boost::numeric::ublas).""" +import io +import json +import unittest +from unittest import mock + +import ast_json +import gen_exports + +HDR = "/b/boost/numeric/ublas/matrix.hpp" +NS = "boost::numeric::ublas::detail" + + +def loc(line=1): + return {"offset": 1, "line": line, "col": 1, "file": HDR} + + +def ns(nid, name, inner): + return {"id": nid, "kind": "NamespaceDecl", "loc": loc(), + "range": {"begin": loc(), "end": loc()}, "name": name, + "inner": inner} + + +def struct(nid, name, line): + return {"id": nid, "kind": "CXXRecordDecl", "loc": loc(line), + "name": name, "tagUsed": "struct", "completeDefinition": True} + + +def directive(nid, target_id, target_name, line): + return {"id": nid, "kind": "UsingDirectiveDecl", "loc": loc(line), + "nominatedNamespace": {"id": target_id, "kind": "NamespaceDecl", + "name": target_name}} + + +def model(): + """namespace boost { namespace numeric { namespace ublas { + struct matrix; + namespace detail { using namespace boost::numeric::ublas; + struct own; } + namespace adl_barrier { struct found_by_adl; } + using namespace adl_barrier; + } } }""" + text = json.dumps(ns("0x1", "boost", [ + ns("0x2", "numeric", [ + ns("0x3", "ublas", [ + struct("0x10", "matrix", 2), + ns("0x4", "detail", [ + directive("0x20", "0x3", "ublas", 4), + struct("0x11", "own", 5), + ]), + ns("0x5", "adl_barrier", [ + struct("0x12", "found_by_adl", 7), + ]), + directive("0x21", "0x5", "adl_barrier", 8), + ]), + ]), + ]), indent=2) + "\n" + return gen_exports.Model(ast_json.TU.from_stream(io.BytesIO(text.encode()))) + + +def policy(**sections): + return gen_exports.Policy({"numeric": sections}) + + +SKIP = {"namespace": NS, "reason": "resize helpers"} + + +class SkipDirectiveTests(unittest.TestCase): + def setUp(self): + self.home = "numeric" + patcher = mock.patch.object(gen_exports, "home_of_file", + side_effect=lambda f: self.home) + patcher.start() + self.addCleanup(patcher.stop) + self.m = model() + + def check(self, pol): + return gen_exports.check_skipped_directives("numeric", self.m, pol) + + def test_undeclared_directive_is_an_error(self): + entries, errors = self.check(policy()) + self.assertEqual(entries, []) + # The ADL barrier is followed, so only the detail directive is named. + self.assertEqual(len(errors), 1) + for part in ("using namespace boost::numeric::ublas;", NS, + "[[numeric.skip-directive]]", "[[numeric.republish]]"): + self.assertIn(part, errors[0]) + + def test_declared_directive_is_listed_with_its_reason(self): + entries, errors = self.check(policy(**{"skip-directive": [SKIP]})) + self.assertEqual(errors, []) + self.assertEqual(entries, [("numeric", "skip-directive", NS, "", + "resize helpers")]) + + def test_republish_declares_the_directive(self): + pol = policy(republish=[{"namespace": NS, "reason": "public"}]) + self.assertEqual(self.check(pol), ([], [])) + + def test_stale_entry_is_an_error(self): + gone = dict(SKIP, namespace="boost::numeric::ublas::gone") + errors = self.check(policy(**{"skip-directive": [SKIP, gone]}))[1] + self.assertEqual(len(errors), 1) + self.assertIn("boost::numeric::ublas::gone", errors[0]) + + def test_adl_barrier_cannot_be_declared(self): + barrier = dict(SKIP, namespace="boost::numeric::ublas") + errors = self.check(policy(**{"skip-directive": [SKIP, barrier]}))[1] + self.assertEqual(len(errors), 1) + self.assertIn("policy skip-directive boost::numeric::ublas:", + errors[0]) + + def test_entry_that_is_also_a_republish_is_an_error(self): + pol = policy(**{"skip-directive": [SKIP], + "republish": [{"namespace": NS, "reason": "public"}]}) + errors = self.check(pol)[1] + self.assertEqual(len(errors), 1) + self.assertIn("also a republish", errors[0]) + + def test_directive_in_another_library_header_is_its_owner_business(self): + self.home = "other" + self.assertEqual(self.check(policy()), ([], [])) + errors = self.check(policy(**{"skip-directive": [SKIP]}))[1] + self.assertEqual(len(errors), 1) + self.assertIn("library that owns its header", errors[0]) + + def test_skipped_directive_republishes_nothing(self): + out = gen_exports.collect_injections("numeric", self.m, {}) + self.assertIn("boost::numeric::ublas::found_by_adl", out) + self.assertFalse([q for q in out if q.startswith(NS + "::")]) + + +if __name__ == "__main__": + unittest.main() From 4b6b374871988d3f1103c5d26d7242d708a92374 Mon Sep 17 00:00:00 2001 From: Zhe Feng Date: Sat, 28 Nov 2026 05:49:54 +0000 Subject: [PATCH 2/3] exports: declare the nine unfollowed using-directive namespaces (skip-directive) The detail groups of #2 (ublas::detail, serialization::cpp_int_detail, sort::blk_detail) and the other directives the generator skips (icl Interval_Set / Interval_Map, poly_collection::common_impl, accumulators numeric::functional / impl, cobalt::this_coro, covered by its extra). No Boost header, macro, test or example spells a name through any of them. Only skipped.txt changes; no .inc / .deps output moves. --- generated/meta/skipped.txt | 12 ++++- tools/export_policy.toml | 108 +++++++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+), 1 deletion(-) diff --git a/generated/meta/skipped.txt b/generated/meta/skipped.txt index e3aab331..7bccd3af 100644 --- a/generated/meta/skipped.txt +++ b/generated/meta/skipped.txt @@ -1,7 +1,10 @@ # Names the export policy (tools/export_policy.toml) guards, drops or -# adds verbatim. GENERATED by tools/gen_exports.py - DO NOT EDIT +# adds verbatim, and the using-directives it does not follow. +# GENERATED by tools/gen_exports.py - DO NOT EDIT # [if ] -- +accumulators skip-directive boost::accumulators::impl -- boost/accumulators/accumulators_fwd.hpp opens `namespace impl { using namespace numeric::operators; }` for the same reason as numeric::functional: the accumulator implementations apply the numeric operators unqualified. accumulators::impl::X is spelled upstream only for impl's own accumulator templates, which are exported directly; none goes through the directive. +accumulators skip-directive boost::numeric::functional -- boost/accumulators/numeric/functional_fwd.hpp declares namespace boost::numeric::operators "for using directives" and pulls it into numeric::functional with `using namespace operators;`, so the functional objects find the std::vector / std::valarray / std::complex operator overloads unqualified. The operators' public spelling is boost::numeric::operators (a user writes their own `using namespace boost::numeric::operators;`); no Boost header, test or example names one as numeric::functional::X. align drop std::alignment_of -- boost::alignment::detail::alignment_of is `using std::alignment_of` only on some compilers; other targets (clang outside x86_64) define a template of that name, which the std re-export would conflict with. asio extra boost::asio::socket_errc -- Like boost::asio::stream_errc: boost/asio/error.hpp simulates the proposed socket_errc scoped enum with a namespace of using-declarations of error:: enumerators, re-created here. asio extra boost::asio::stream_errc -- boost/asio/error.hpp simulates the proposed stream_errc / socket_errc scoped enums with namespaces that hold only using-declarations of error:: enumerators (the cpp14 blocking_tcp_echo_server example compares with boost::asio::stream_errc::eof). The generator collects declared entities, not using-declarations, so those namespaces are re-created here. @@ -96,6 +99,7 @@ cobalt extra boost::cobalt::this_coro -- boost/cobalt/this_coro.hpp brings asio' cobalt guard boost::cobalt::io::sctp if defined(IPPROTO_SCTP) -- boost/cobalt/io/endpoint.hpp declares the SCTP protocol constants only where the platform defines IPPROTO_SCTP (MinGW does, MSVC's SDK does not). cobalt guard boost::cobalt::io::sctp_v4 if defined(IPPROTO_SCTP) -- boost/cobalt/io/endpoint.hpp declares the SCTP protocol constants only where the platform defines IPPROTO_SCTP (MinGW does, MSVC's SDK does not). cobalt guard boost::cobalt::io::sctp_v6 if defined(IPPROTO_SCTP) -- boost/cobalt/io/endpoint.hpp declares the SCTP protocol constants only where the platform defines IPPROTO_SCTP (MinGW does, MSVC's SDK does not). +cobalt skip-directive boost::cobalt::this_coro -- `using namespace asio::this_coro;` is a public spelling (cobalt::this_coro::executor). The [[cobalt.extra]] for this namespace re-declares the names, following the documented outline of boost/cobalt/this_coro.hpp; the generator does not follow the directive itself. config guard boost::int128_type if defined(BOOST_HAS_INT128) -- M3 hand-guard (M9: moved to config.inc): suffix.hpp defines int128_type only where BOOST_HAS_INT128. config guard boost::uint128_type if defined(BOOST_HAS_INT128) -- M3 hand-guard (M9: moved to config.inc): suffix.hpp defines uint128_type only where BOOST_HAS_INT128. container extra -- allocator_traits::construct places elements with the global operator new(std::size_t, void*, boost_container_new_t) of boost/container/detail/placement_new.hpp. A consumer TU that instantiates it (pmr::vector::resize, in the json documentation) looks the operator up at the point of instantiation, where only exported declarations are visible; the generator exports boost:: names only, so the tag type and its placement operators are exported here. gcc only: on clang the using-declarations re-export every global operator new, and libc++'s own aligned allocations in another module's instantiations become ambiguous (`call to 'operator new' is ambiguous`, tests/statechart.cpp); clang reaches the operator through src/json.cppm instead. @@ -213,6 +217,8 @@ hof guard boost::hof::detail::can_be_called_impl if !BOOST_HOF_NO_EXPRESSION_SFI hof guard boost::hof::detail::eval_helper if !BOOST_HOF_NO_ORDERED_BRACE_INIT -- C2 platform guard: eval_helper is the !NO_ORDERED_BRACE_INIT branch of apply_eval.hpp (config.hpp: _MSC_VER → 1). hof guard boost::hof::operators::decrement if !defined(_MSC_VER) -- C2 platform guard: operators::decrement is the #ifndef _MSC_VER branch of placeholders.hpp (MSVC 2017 ICE on ++/-- constexpr). hof guard boost::hof::operators::increment if !defined(_MSC_VER) -- C2 platform guard: operators::increment is the #ifndef _MSC_VER branch of placeholders.hpp (MSVC 2017 ICE on ++/-- constexpr). +icl skip-directive boost::icl::Interval_Map -- boost/icl/detail/interval_map_algo.hpp: the interval_map counterpart of Interval_Set (`namespace Interval_Map { using namespace segmental; }`), with the same reasoning: an implementation namespace, spelled only inside icl's headers and only for its own members. +icl skip-directive boost::icl::Interval_Set -- boost/icl/detail/interval_set_algo.hpp opens `namespace Interval_Set { using namespace segmental; }`: the algorithm namespace behind the interval_set functions of boost/icl/concept/ uses icl::segmental's helpers unqualified. Interval_Set::X is spelled only inside icl's own headers and only for Interval_Set's own templates, which are exported directly; the segmental names keep their spelling boost::icl::segmental::X. interprocess guard boost::interprocess::basic_managed_windows_shared_memory if defined(_WIN32) -- The Windows shared-memory and synchronization surface (detail/win32_api.hpp chain); POSIX interprocess never declares it. interprocess guard boost::interprocess::ipcdetail::do_winapi_wait if defined(_WIN32) -- The Windows shared-memory and synchronization surface (detail/win32_api.hpp chain); POSIX interprocess never declares it. interprocess guard boost::interprocess::ipcdetail::file_time_to_microseconds if defined(_WIN32) -- The Windows shared-memory and synchronization surface (detail/win32_api.hpp chain); POSIX interprocess never declares it. @@ -469,15 +475,18 @@ multiprecision guard boost::multiprecision::detail::addcarry_limb if defined(BOO multiprecision guard boost::multiprecision::detail::subborrow_limb if defined(BOOST_MP_HAS_IMMINTRIN_H) -- M11 platform guard: cpp_int/intel_intrinsics.hpp declares subborrow_limb only under BOOST_MP_HAS_IMMINTRIN_H (see addcarry_limb guard for rationale). multiprecision guard boost::multiprecision::int128_type if defined(BOOST_HAS_INT128) -- M12 platform guard: detail/standalone_config.hpp defines int128_type only under BOOST_HAS_INT128 (off under the clang-msvc flavor). multiprecision guard boost::multiprecision::uint128_type if defined(BOOST_HAS_INT128) -- M12 platform guard: as above (uint128_type). +multiprecision skip-directive boost::serialization::cpp_int_detail -- boost/multiprecision/cpp_int/serialize.hpp opens `namespace cpp_int_detail { using namespace boost::multiprecision; using namespace boost::multiprecision::backends; }` so its do_serialize helpers can name cpp_int_backend and number unqualified. The public entry point is the boost::serialization::serialize overload (exported), found by Boost.Serialization; upstream spells cpp_int_detail::X only for the helpers declared there (do_serialize, is_binary_archive, exported directly). Following the directive would re-spell all of multiprecision under boost::serialization::cpp_int_detail (355 names before #1). nowide guard boost::nowide::detail::console_input_buffer if defined(_WIN32) -- M11 platform guard: console_input_buffer is the windows console machinery (detail/console_buffer.hpp); POSIX nowide uses std:: streams directly. nowide guard boost::nowide::detail::console_output_buffer if defined(_WIN32) -- M11 platform guard: console_output_buffer is the windows console machinery (detail/console_buffer.hpp); POSIX nowide uses std:: streams directly. nowide guard boost::nowide::detail::stat if defined(_WIN32) -- M11 platform guard: detail::stat is the BOOST_WINDOWS branch of stat.hpp; POSIX exposes ::stat via a using-declaration instead. nowide guard boost::nowide::detail::winconsole_istream if defined(_WIN32) -- M11 platform guard: winconsole_istream is the windows console stream branch of iostream.hpp; POSIX takes std:: streams directly. nowide guard boost::nowide::detail::winconsole_ostream if defined(_WIN32) -- M11 platform guard: winconsole_ostream is the windows console stream branch of iostream.hpp; POSIX takes std:: streams directly. numeric guard boost::numeric::ublas::same_impl_ex if !defined(NDEBUG) && !defined(BOOST_UBLAS_NDEBUG) -- Boost.uBLAS declares same_impl_ex only when size checks are on; a release build (NDEBUG) takes BOOST_UBLAS_USE_FAST_SAME and never declares it. +numeric skip-directive boost::numeric::ublas::detail -- boost/numeric/ublas/matrix.hpp and triangular.hpp open `namespace detail { using namespace boost::numeric::ublas; }` so the matrix_resize_preserve helpers can name uBLAS types unqualified. It is not a public spelling: every ublas::detail::X in Boost's headers, macros, tests and examples names a member declared in ublas::detail (tensor_expression, retrieve_extents, recursive::mtv, ...), exported directly. Following the directive would re-spell all of boost::numeric::ublas under detail (356 names, reachable from 15 modules, before #1). pfr guard boost::pfr::detail::clang_wrapper_t if defined(__clang__) -- M9 platform guard: clang_wrapper_t is the clang-only NTTP wrapper (core_name20_static.hpp #ifdef __clang__ branch). pfr guard boost::pfr::detail::fields_count_dispatch_impl if BOOST_PFR_USE_CPP26_REFLECTION || BOOST_PFR_USE_CPP26 -- M9 platform guard: fields_count_dispatch_impl exists only under the C++26 reflection / structured-bindings branches (fields_count.hpp). poly_collection guard boost::mpl::item_by_order_impl if defined(__GNUC__) -- M9 platform guard: gcc-preprocessed mpl map headers only. +poly_collection skip-directive boost::poly_collection::common_impl -- boost/poly_collection/detail/poly_collection.hpp opens `namespace common_impl { using namespace detail; }` for its own implementation. common_impl is the base of base_collection / function_collection / any_collection / variant_collection, which are exported under boost::poly_collection; upstream spells common_impl::X only for common_impl::poly_collection itself. process guard boost::asio::windows::basic_object_handle if defined(_WIN32) -- The boost::asio::windows handles that process's Windows launcher reaches (stream_handle, basic_object_handle) exist only on Windows. process guard boost::asio::windows::stream_handle if defined(_WIN32) -- The boost::asio::windows handles that process's Windows launcher reaches (stream_handle, basic_object_handle) exist only on Windows. process guard boost::process::v1::detail::windows::apply_out_handles if defined(_WIN32) -- M11 platform guard: v1 detail windows impls (incl. the NT workaround block below) are declared only by the windows GMF branches. @@ -622,6 +631,7 @@ range guard std::random_shuffle if defined(__GLIBCXX__) -- M9 platform guard: st signals2 guard boost::signals2::detail::critical_section if defined(BOOST_HAS_WINTHREADS) -- The critical-section mutex is the Windows-threads branch of signals2's lightweight mutex; POSIX uses pthread. signals2 guard boost::signals2::detail::critical_section_debug if defined(BOOST_HAS_WINTHREADS) -- The critical-section mutex is the Windows-threads branch of signals2's lightweight mutex; POSIX uses pthread. signals2 guard boost::signals2::detail::rtl_critical_section if defined(BOOST_HAS_WINTHREADS) -- The critical-section mutex is the Windows-threads branch of signals2's lightweight mutex; POSIX uses pthread. +sort skip-directive boost::sort::blk_detail -- boost/sort/block_indirect_sort/blk_detail/block.hpp opens `namespace blk_detail { using namespace boost::sort::common; }`: the implementation of block_indirect_sort uses the common range / stack helpers unqualified. The public entry point is boost::sort::block_indirect_sort; upstream spells blk_detail::X only for blk_detail's own templates (exported directly), and the common helpers keep their spelling boost::sort::common::X. Following the directive would re-spell boost::sort::common under blk_detail (55 names before #1). system guard boost::system::detail::local_free if defined(BOOST_WINDOWS_API) -- M6 platform guard: snapshot = mingw flavor; these boost/system/detail entities exist only under BOOST_WINDOWS_API (system_category_message_win32.hpp / condition). system guard boost::system::detail::message_cp_win32 if defined(BOOST_WINDOWS_API) -- M6 platform guard: snapshot = mingw flavor; these boost/system/detail entities exist only under BOOST_WINDOWS_API (system_category_message_win32.hpp / condition). system guard boost::system::detail::system_category_condition_win32 if defined(BOOST_WINDOWS_API) -- M6 platform guard: as above. diff --git a/tools/export_policy.toml b/tools/export_policy.toml index 344fa9c2..4a6f82d7 100644 --- a/tools/export_policy.toml +++ b/tools/export_policy.toml @@ -453,6 +453,31 @@ names = ["boost::mpl::item_by_order_impl"] # mapping module, where the constants live (one export owner). add = ["macros"] +# -------------------------------------------------------------------------- +# accumulators + +[[accumulators.skip-directive]] +namespace = "boost::numeric::functional" +reason = ''' +boost/accumulators/numeric/functional_fwd.hpp declares namespace +boost::numeric::operators "for using directives" and pulls it into +numeric::functional with `using namespace operators;`, so the functional +objects find the std::vector / std::valarray / std::complex operator overloads +unqualified. The operators' public spelling is boost::numeric::operators (a +user writes their own `using namespace boost::numeric::operators;`); no Boost +header, test or example names one as numeric::functional::X. +''' + +[[accumulators.skip-directive]] +namespace = "boost::accumulators::impl" +reason = ''' +boost/accumulators/accumulators_fwd.hpp opens `namespace impl { using +namespace numeric::operators; }` for the same reason as numeric::functional: +the accumulator implementations apply the numeric operators unqualified. +accumulators::impl::X is spelled upstream only for impl's own accumulator +templates, which are exported directly; none goes through the directive. +''' + # -------------------------------------------------------------------------- # asio @@ -690,6 +715,16 @@ lines = [ "using boost::asio::this_coro::throw_if_cancelled;", ] +[[cobalt.skip-directive]] +namespace = "boost::cobalt::this_coro" +reason = ''' +`using namespace asio::this_coro;` is a public spelling +(cobalt::this_coro::executor). The [[cobalt.extra]] for this namespace +re-declares the names, following the documented outline of +boost/cobalt/this_coro.hpp; the generator does not follow the directive +itself. +''' + [[cobalt.guard]] if = "defined(IPPROTO_SCTP)" reason = ''' @@ -1190,6 +1225,29 @@ names = [ "boost::hof::operators::increment", ] +# -------------------------------------------------------------------------- +# icl + +[[icl.skip-directive]] +namespace = "boost::icl::Interval_Set" +reason = ''' +boost/icl/detail/interval_set_algo.hpp opens `namespace Interval_Set { using +namespace segmental; }`: the algorithm namespace behind the interval_set +functions of boost/icl/concept/ uses icl::segmental's helpers unqualified. +Interval_Set::X is spelled only inside icl's own headers and only for +Interval_Set's own templates, which are exported directly; the segmental names +keep their spelling boost::icl::segmental::X. +''' + +[[icl.skip-directive]] +namespace = "boost::icl::Interval_Map" +reason = ''' +boost/icl/detail/interval_map_algo.hpp: the interval_map counterpart of +Interval_Set (`namespace Interval_Map { using namespace segmental; }`), with +the same reasoning: an implementation namespace, spelled only inside icl's +headers and only for its own members. +''' + # -------------------------------------------------------------------------- # interprocess @@ -1581,6 +1639,20 @@ names = [ # -------------------------------------------------------------------------- # multiprecision +[[multiprecision.skip-directive]] +namespace = "boost::serialization::cpp_int_detail" +reason = ''' +boost/multiprecision/cpp_int/serialize.hpp opens `namespace cpp_int_detail { +using namespace boost::multiprecision; using namespace +boost::multiprecision::backends; }` so its do_serialize helpers can name +cpp_int_backend and number unqualified. The public entry point is the +boost::serialization::serialize overload (exported), found by +Boost.Serialization; upstream spells cpp_int_detail::X only for the helpers +declared there (do_serialize, is_binary_archive, exported directly). Following +the directive would re-spell all of multiprecision under +boost::serialization::cpp_int_detail (355 names before #1). +''' + [[multiprecision.guard]] if = "defined(BOOST_HAS_INT128)" reason = ''' @@ -1730,6 +1802,19 @@ names = [ # -------------------------------------------------------------------------- # numeric +[[numeric.skip-directive]] +namespace = "boost::numeric::ublas::detail" +reason = ''' +boost/numeric/ublas/matrix.hpp and triangular.hpp open `namespace detail { +using namespace boost::numeric::ublas; }` so the matrix_resize_preserve +helpers can name uBLAS types unqualified. It is not a public spelling: every +ublas::detail::X in Boost's headers, macros, tests and examples names a member +declared in ublas::detail (tensor_expression, retrieve_extents, recursive::mtv, +...), exported directly. Following the directive would re-spell all of +boost::numeric::ublas under detail (356 names, reachable from 15 modules, +before #1). +''' + [[numeric.guard]] if = "!defined(NDEBUG) && !defined(BOOST_UBLAS_NDEBUG)" reason = ''' @@ -1766,6 +1851,16 @@ names = [ # -------------------------------------------------------------------------- # poly_collection +[[poly_collection.skip-directive]] +namespace = "boost::poly_collection::common_impl" +reason = ''' +boost/poly_collection/detail/poly_collection.hpp opens `namespace common_impl +{ using namespace detail; }` for its own implementation. common_impl is the +base of base_collection / function_collection / any_collection / +variant_collection, which are exported under boost::poly_collection; upstream +spells common_impl::X only for common_impl::poly_collection itself. +''' + [[poly_collection.guard]] if = "defined(__GNUC__)" reason = ''' @@ -2303,6 +2398,19 @@ names = [ # any :: segment # -------------------------------------------------------------------------- # sort +[[sort.skip-directive]] +namespace = "boost::sort::blk_detail" +reason = ''' +boost/sort/block_indirect_sort/blk_detail/block.hpp opens `namespace +blk_detail { using namespace boost::sort::common; }`: the implementation of +block_indirect_sort uses the common range / stack helpers unqualified. The +public entry point is boost::sort::block_indirect_sort; upstream spells +blk_detail::X only for blk_detail's own templates (exported directly), and the +common helpers keep their spelling boost::sort::common::X. Following the +directive would re-spell boost::sort::common under blk_detail (55 names before +#1). +''' + [sort.facade] omit-imports = ["range"] reason = ''' From c4f4966f0678ddbadc357d6b97453d763b757a39 Mon Sep 17 00:00:00 2001 From: Zhe Feng Date: Sat, 28 Nov 2026 05:49:54 +0000 Subject: [PATCH 3/3] docs: the skip-directive policy rule; design record --- .../docs/2026-11-28-skip-directive-design.md | 120 ++++++++++++++++++ .agents/docs/README.md | 4 +- docs/architecture.md | 7 +- docs/architecture.zh.md | 6 +- 4 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 .agents/docs/2026-11-28-skip-directive-design.md diff --git a/.agents/docs/2026-11-28-skip-directive-design.md b/.agents/docs/2026-11-28-skip-directive-design.md new file mode 100644 index 00000000..7700d6b2 --- /dev/null +++ b/.agents/docs/2026-11-28-skip-directive-design.md @@ -0,0 +1,120 @@ +--- +subject: generator +status: landed +--- + +# 不跟随的 using 指令必须声明:策略 `skip-directive` + +来源:issue #2 的第二条验收标准(detail 命名空间组确认可以丢弃,并在 +`skipped.txt` 中说明原因),以及"建议方向"第 2 条("不要静默丢弃")。叠在 +[`republish`](2026-11-28-dll-fs-republish-design.md)(PR #9)之上。 + +## 问题 + +`collect_injections` 只跟随 ADL 屏障形态的 `using namespace`(目标嵌套在指令自身 +的命名空间里)。其余指令被直接跳过,也不留任何记录。issue #2 中有三组名称是这样 +丢掉的,当时只给出了初步判断"detail,丢掉可以接受,需确认": + +| 名称数 | 命名空间 | 指令 | +|---:|---|---| +| 356 | `boost::numeric::ublas::detail` | `boost/numeric/ublas/matrix.hpp`、`triangular.hpp`:`using namespace boost::numeric::ublas;` | +| 355 | `boost::serialization::cpp_int_detail` | `boost/multiprecision/cpp_int/serialize.hpp`:`using namespace boost::multiprecision;`、`using namespace boost::multiprecision::backends;` | +| 55 | `boost::sort::blk_detail` | `boost/sort/block_indirect_sort/blk_detail/block.hpp`:`using namespace boost::sort::common;` | + +## 调查 + +**全部被跳过的指令。** 给跳过分支临时加了记录,做一次冷的全量生成 +(`--no-cache`)。116 个库中一共只有 12 处,分属 10 个(库,命名空间): + +| 库 | 指令所在命名空间 | 目标 | +|---|---|---| +| accumulators | `boost::numeric::functional` | `boost::numeric::operators` | +| accumulators | `boost::accumulators::impl` | `boost::numeric::operators` | +| cobalt | `boost::cobalt::this_coro` | `boost::asio::this_coro` | +| dll | `boost::dll::fs` | `boost::filesystem`(已由 `republish` 处理) | +| icl | `boost::icl::Interval_Set` | `boost::icl::segmental` | +| icl | `boost::icl::Interval_Map` | `boost::icl::segmental` | +| multiprecision | `boost::serialization::cpp_int_detail` | `boost::multiprecision`、`…::backends` | +| numeric | `boost::numeric::ublas::detail` | `boost::numeric::ublas`(两处) | +| poly_collection | `boost::poly_collection::common_impl` | `boost::poly_collection::detail` | +| sort | `boost::sort::blk_detail` | `boost::sort::common` | + +ublas 的指令出现在 15 个模块的 TU 里,但只有 numeric 拥有那两个头文件;按 +`home_of_file` 的规则,也只有 numeric 会注入它。 + +**有没有公开写法依赖这些指令。** 一个名字只经由指令可达,指的是它在目标命名空间 +中导出、在指令所在命名空间中没有直接声明。在 `upstream/boost/boost`(头文件和宏) +和 `upstream/boost/libs`(测试、示例)中搜索每个命名空间的限定写法 +(`ublas::detail::X`、`cpp_int_detail::X`、`blk_detail::X`、`Interval_Set::X`、 +`Interval_Map::X`、`common_impl::X`、`accumulators::impl::X`、 +`functional::operator…`),再和生成的 `.inc` 对照: + +- ublas::detail:11 个不同的名字,9 个是 ublas::detail 中直接声明并已导出的成员 + (`tensor_expression`、`retrieve_extents`、`make_binary_tensor_expression` 等, + `BOOST_UBLAS_*` 宏展开用到的也是这些)。另外两个,`recursive` 是嵌套命名空间 + (`recursive::mtv` 已导出),`make_lambda` 只出现在注释里。 +- cpp_int_detail、blk_detail、Interval_Set、Interval_Map、common_impl、 + accumulators::impl:所有写法都指向该命名空间自己的成员,且全部已直接导出。 +- 没有任何代码写 `using namespace …::detail;` 去打开这些命名空间。 +- numeric::functional / accumulators::impl:没有经由它们写运算符的代码。 + `functional_fwd.hpp` 中 `namespace operators {}` 旁的上游注释是 "For using + directives"。 + +模板实例化不受影响:GMF 中头文件里的非限定查找在定义处进行,该处能看到指令; +导出只决定导入方自己能写出的名字。 + +结论:三组 detail 名称可以丢弃。另外四处(icl ×2、poly_collection、 +accumulators ×2)也都是实现上的便利。cobalt 的指令确实是公开写法 +(`cobalt::this_coro::executor`),但已经由 `[[cobalt.extra]]` 处理。 + +## 决定 + +新增策略条目 `[[.skip-directive]]`,字段为 `namespace` 和 `reason`。 + +- `check_skipped_directives` 在每个重新解析的库上运行。它找出该库自身(或 + "shared")头文件中所有指向 `boost::` 命名空间、又不是 ADL 屏障形态的 using + 指令。每个这样的命名空间都必须由 `skip-directive` 或 `republish` 声明,否则 + 生成失败,报错中给出指令、目标和两种写法。 +- 以下情况同样报错: + - `skip-directive` 没有匹配到任何指令,包括 ADL 屏障形态(会被跟随的)和别的 + 库头文件中的指令; + - 同一个命名空间同时是 `republish`。 +- 每个条目以 ` skip-directive -- ` 写进 + `skipped.txt`,文件头的说明随之改为也包括"不跟随的 using 指令"。 +- 缓存:条目是该库策略段的一部分,策略摘要在缓存 key 里;TU 不变时指令也不变。 + 所以缓存命中时不需要重新检查,`skipped` 条目随缓存一起回放。 +- 写入了 9 个条目(上表除 dll 外的各行)。每个 reason 写明指令的位置和用途、 + 公开写法是什么,以及上游写法的核对结果。detail 三组还写明了跟随时会多出的名称数。 +- 输出:只有 `skipped.txt` 多了 9 行,任何 `.inc` / `.deps` 都没有变化。 + +## 否决的做法 + +- **只给 issue 中的三组 detail 写条目,其余仍静默跳过**:下一次升级 Boost 时 + 新增的指令照样会悄悄丢掉名称。全仓只有 12 处,全部声明的成本很低,此后每处新增 + 都必须有人审查。 +- **按命名空间名中是否含 `detail` 自动放行**:`Interval_Set`、`common_impl`、 + `functional` 都不含 `detail`。名字也说明不了某个写法是不是公开的。 +- **把 cobalt 改成 `republish`**:会多导出 asio 的 `reset_cancellation_state_0_t` + 等 5 个辅助类型,改变 cobalt 的导出面,不属于本轮范围。这里记作 + `skip-directive`,reason 指向现有的 `extra`。 +- **`skip-directive` 按(命名空间,目标)逐条声明**:cpp_int_detail 的两条指令 + 理由相同。按命名空间声明已经能发现新增的指令所在命名空间,同一命名空间里新增的 + 目标在审查 reason 时一并核对。 + +## 顺带发现(未处理) + +accumulators 的 GMF 包含 `boost/accumulators/numeric/functional/vector.hpp` 等 +头文件,但 `boost::numeric::operators` 中的运算符模板(`operator/(std::vector…)` +等)没有被任何模块导出。这与 using 指令无关,留待单独分析。 + +## 测试 + +`tools/tests/test_gen_exports_skip_directive.py`,覆盖: + +- 未声明的指令报错; +- 声明后列出条目; +- `republish` 视为已声明; +- 过期条目、ADL 屏障条目报错; +- 与 `republish` 重复报错; +- 别的库头文件中的指令; +- 不跟随时不产生注入。 diff --git a/.agents/docs/README.md b/.agents/docs/README.md index 6c66ac8a..92a7318c 100644 --- a/.agents/docs/README.md +++ b/.agents/docs/README.md @@ -27,7 +27,7 @@ - `todos/` 放尚未完成的工作项,它们不是决定的记录。 - 移动或改名用 `tools/doc-tools/move_record.py`,它同时改写仓库中对该文件的引用。 -共 29 篇记录(其中 0 篇已归档),1 项待办。 +共 30 篇记录(其中 0 篇已归档),1 项待办。 ## 进行中 @@ -45,6 +45,7 @@ ### generator +- [不跟随的 using 指令必须声明:策略 `skip-directive`](2026-11-28-skip-directive-design.md) — landed - [`boost::dll::fs` 跟随 `boost::filesystem`:策略 `republish`](2026-11-28-dll-fs-republish-design.md) — landed ### tests @@ -64,6 +65,7 @@ ### 2026-11 +- [不跟随的 using 指令必须声明:策略 `skip-directive`](2026-11-28-skip-directive-design.md) — landed - [`boost::dll::fs` 跟随 `boost::filesystem`:策略 `republish`](2026-11-28-dll-fs-republish-design.md) — landed - [PR #5 第二轮评审的 [nit] 修复:覆盖率按测试程序列出的用例核对](2026-11-21-pr5-review-nits-design.md) — active - [子工程复用根工程的构建产物,mcpp 升级到 2026.11.20.1](2026-11-20-sub-project-build-reuse-design.md) — active diff --git a/docs/architecture.md b/docs/architecture.md index b76b70cf..3b1319ba 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -169,7 +169,9 @@ libclang, no Python bindings, no LLVM release archive. that give entities their public spelling (ADL barriers, `detail` re-exports). A `using namespace` is followed only in the ADL-barrier shape (the target is nested in the directive's own namespace); one that names another library's - namespace is followed when the policy declares it (`republish` below). + namespace is followed when the policy declares it (`republish` below). Every + other directive in a library's own headers must be declared `skip-directive` + with its reason, or generation fails, so no spelling is dropped silently. - **Signature closure**: entities named by the candidates' signatures (parameters, results, bases, fields, typedef targets — with typedefs looked through), so the API's own types are exported with it. @@ -194,13 +196,14 @@ written reason and applied by the generator, never patched into its output: | `[[.drop]]` | never export the matching names / namespaces | | `[[.extra]]` | verbatim declarations (the gcc `extern template` vtable workarounds) | | `[[.republish]]` | the namespace holds `using namespace ;` for another library's namespace: every name that library exports directly in `` is re-exported through it, optionally under `if` (`boost::dll::fs` follows `boost::filesystem`) | +| `[[.skip-directive]]` | the namespace's `using namespace X;` is an implementation convenience, not a public spelling (`namespace ublas { namespace detail { using namespace boost::numeric::ublas; } }`): it is not followed, and the reason is recorded | | `add` | names no collector reaches (body-only or ADL-only references) | | `gmf`, `defines`, `facade-includes` | the bundle's include set and macros; facade-only includes | | `inline-namespaces` | export a macro-selected inline namespace through its parent | | `[.deps]` | module edge corrections; edges of the hand-written special modules | `generated/meta/skipped.txt` lists every name a rule guards, drops or adds, and -each `extra` / `republish` namespace, so the boundary is reviewable in one file, +each `extra` / `republish` / `skip-directive` namespace, so the boundary is reviewable in one file, and `generated/meta/api-surface.json` records the generator identity (clang release, target, defines) and per-library GMF, export count and edges. A diff after a compiler update therefore shows as a diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 1b5dc127..a1d9d803 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -149,7 +149,8 @@ clang++ -std=c++23 --target=x86_64-w64-mingw32 --sysroot= \ - **using 注入**:赋予实体公开拼写的命名空间作用域 `using X::y;` / `using namespace X;`(ADL 屏障、`detail` 再导出)。`using namespace` 只在 ADL 屏障形态下跟随(目标嵌套在指令自身的命名空间内);指向其他库命名空间的指令, - 由策略声明后才跟随(见下文 `republish`)。 + 由策略声明后才跟随(见下文 `republish`)。库自身头文件中的其余指令必须声明为 + `skip-directive` 并写明原因,否则生成失败,不会静默丢失任何写法。 - **签名闭包**:候选签名中点名的实体(形参、返回值、基类、字段、typedef 目标—— typedef 会被看穿),使 API 自身的类型随之导出。 - **归属**:按依赖优先的顺序处理各库;第一个认领实体的库拥有它,之后的库在 @@ -173,10 +174,11 @@ clang++ -std=c++23 --target=x86_64-w64-mingw32 --sysroot= \ | `add` | 没有收集器能到达的名字(只在函数体或 ADL 中出现的引用) | | `gmf`、`defines`、`facade-includes` | bundle 的 include 集合与宏;仅门面使用的 include | | `inline-namespaces` | 经由父命名空间导出由宏选择的 inline 命名空间 | +| `[[.skip-directive]]` | 该命名空间中的 `using namespace X;` 只是实现上的便利,不是公开写法(`namespace ublas { namespace detail { using namespace boost::numeric::ublas; } }`):不跟随,并记录原因 | | `[.deps]` | 模块边修正;手写特殊模块的边 | `generated/meta/skipped.txt` 列出每条规则守卫、丢弃或添加的名字,以及每个 -`extra` / `republish` 命名空间,边界可以在一个文件里审阅;`generated/meta/api-surface.json` 记录生成器身份(clang 版本、目标、 +`extra` / `republish` / `skip-directive` 命名空间,边界可以在一个文件里审阅;`generated/meta/api-surface.json` 记录生成器身份(clang 版本、目标、 宏定义)以及每个库的 GMF、导出数和边。因此编译器升级后的差异会显示为生成器 变化,而不是无法解释的 API 变化。