From 916c8ee26baf6a7fc624f97487c612cb6562d27f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:50:14 +0000 Subject: [PATCH 1/6] build: never pack the per-module Stdlib projects The tree-shaking projects under src/Sharpy.Stdlib/modules/ (#696) compile code ported from CPython (Fnmatch, Itertools, Os, Shutil, Difflib, ...) but were packable by default, declaring Apache-2.0 OR MIT and packing no THIRD-PARTY-NOTICES.txt. Nothing packs them today (release.yml packs Cli, Core, Stdlib and Compiler by path; build_tools, .claude/scripts and the Playground pack nothing), so this closes the door before anything does. MSBuild resolves IsPackable to false for Sharpy.Stdlib.Fnmatch and still true for Sharpy.Stdlib (control). Guard: test_package_licenses.py reads the modules' Directory.Build.props (IsPackable set once, to false) and refuses any project-level override. Mutation: IsPackable false -> true in the props: red (1 failed, 13 passed: "Directory.Build.props: sets IsPackable ['true']"); restored with cp + cmp: green (14 passed). Refs #2602 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/tests/test_package_licenses.py | 83 +++++++++++++++++++ .../modules/Directory.Build.props | 5 ++ 2 files changed, 88 insertions(+) diff --git a/build_tools/tests/test_package_licenses.py b/build_tools/tests/test_package_licenses.py index 5636ccb980..843ba8d5bc 100644 --- a/build_tools/tests/test_package_licenses.py +++ b/build_tools/tests/test_package_licenses.py @@ -11,6 +11,8 @@ import re from pathlib import Path +import pytest + REPO = Path(__file__).resolve().parent.parent.parent # SPDX ids checked against https://spdx.org/licenses/ (isOsiApproved or isFsfLibre true). @@ -194,3 +196,84 @@ def test_the_retired_id_pattern_matches_only_the_id(): "PSF License Version 2", ): assert not _RETIRED_IDS.search(text), text + + +# ---- The per-module Stdlib projects never pack ---- +# +# src/Sharpy.Stdlib/modules/ holds one tree-shaking project per module (#696). They compile code +# ported from CPython (Fnmatch, Itertools, Os, Shutil, Difflib, ...) but carry neither +# THIRD-PARTY-NOTICES.txt nor the Python-2.0 term that SharpyLang.Stdlib's package does, so a +# `dotnet pack` of one would ship a port under `Apache-2.0 OR MIT` alone (#2602 follow-up, owner +# 2026-11-20). Their shared Directory.Build.props sets IsPackable to false, and no project there +# may set it back. + +MODULES = "src/Sharpy.Stdlib/modules" +_IS_PACKABLE = re.compile(r"]*>([^<]*)") + + +def unpackable_problems(modules: Path) -> list[str]: + props = modules / "Directory.Build.props" + text = props.read_text(encoding="utf-8") if props.is_file() else "" + values = _IS_PACKABLE.findall(text) + problems = [] + if [v.strip().lower() for v in values] != ["false"]: + problems.append( + f"{props.name}: sets IsPackable {values!r}; it must set it once, to false" + ) + for project in sorted(modules.glob("*.csproj")): + for value in _IS_PACKABLE.findall(project.read_text(encoding="utf-8")): + if value.strip().lower() != "false": + problems.append( + f"{project.name}: overrides IsPackable with {value!r}; the per-module " + "projects never pack" + ) + return problems + + +def test_the_module_scan_sees_the_per_module_projects(): + # Positive control: the projects that compile CPython ports are among those checked. + names = {p.name for p in (REPO / MODULES).glob("*.csproj")} + assert { + "Sharpy.Stdlib.Fnmatch.csproj", + "Sharpy.Stdlib.Itertools.csproj", + "Sharpy.Stdlib.Os.csproj", + "Sharpy.Stdlib.Shutil.csproj", + "Sharpy.Stdlib.Difflib.csproj", + } <= names + + +def test_no_per_module_stdlib_project_is_packable(): + problems = unpackable_problems(REPO / MODULES) + assert not problems, "\n".join(problems) + + +_PROPS = "\n \n false\n \n\n" +_PROJECT = '\n\n' +_OVERRIDE = '\n \n true\n \n\n' + + +def test_the_packable_check_accepts_the_shared_default(tmp_path: Path): + (tmp_path / "Directory.Build.props").write_text(_PROPS, encoding="utf-8") + (tmp_path / "Sharpy.Stdlib.Fnmatch.csproj").write_text(_PROJECT, encoding="utf-8") + assert unpackable_problems(tmp_path) == [] + + +def test_the_packable_check_refuses_a_project_override(tmp_path: Path): + (tmp_path / "Directory.Build.props").write_text(_PROPS, encoding="utf-8") + (tmp_path / "Sharpy.Stdlib.Os.csproj").write_text(_OVERRIDE, encoding="utf-8") + problems = unpackable_problems(tmp_path) + assert len(problems) == 1 and "Sharpy.Stdlib.Os.csproj: overrides" in problems[0], ( + problems + ) + + +@pytest.mark.parametrize( + "props", ["\n\n", _PROPS.replace("false", "true")] +) +def test_the_packable_check_refuses_a_packable_default(tmp_path: Path, props: str): + (tmp_path / "Directory.Build.props").write_text(props, encoding="utf-8") + (tmp_path / "Sharpy.Stdlib.Fnmatch.csproj").write_text(_PROJECT, encoding="utf-8") + problems = unpackable_problems(tmp_path) + assert ( + len(problems) == 1 and "Directory.Build.props: sets IsPackable" in problems[0] + ), problems diff --git a/src/Sharpy.Stdlib/modules/Directory.Build.props b/src/Sharpy.Stdlib/modules/Directory.Build.props index f4cd917b5c..951f46ec68 100644 --- a/src/Sharpy.Stdlib/modules/Directory.Build.props +++ b/src/Sharpy.Stdlib/modules/Directory.Build.props @@ -18,6 +18,11 @@ true CS1574;CS1580;CS1591 $(NoWarn);CA1305;CA1307 + + false From d1221000acf8aeb4e11018e083cea1556459372e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:53:19 +0000 Subject: [PATCH 2/6] build: credit API summaries taken from CPython docstrings The #2777 review found one-line API summaries copied word for word from CPython 3.15 Lib docstrings, mostly in files the #2602 census marks "behaviour". They are documentation, not code, so the files keep no PSF header; THIRD-PARTY-NOTICES.txt gains one section in the CPython part, "API documentation summaries adapted from CPython docstrings", naming the 17 files (40 summaries: 33 in behaviour files, 7 in the fnmatch and shutil ports), the Lib modules they come from, and the PSF licence text that follows by reference. Method (the reviewer's): a summary matches when its first paragraph (a C# : its whole text or first sentence), whitespace collapsed, case and a final full stop ignored, equals the first paragraph of a module, class or function docstring longer than 30 characters in CPython 3.15.2's Lib (test packages, idlelib, site-packages not read); C# generated from a .spy file is skipped. No later sentence of a matched summary appears in a CPython docstring. Guard: test_third_party_notices.py runs that matcher over Sharpy.Core and Sharpy.Stdlib against python3.15's Lib (the pytest interpreter when it is 3.15, else python3.15 on PATH, else skip with a reason) and requires the section's list to equal the matched set. Unit tests pin the index rule and both refusal directions without the oracle. Mutations: (a) drop src/Sharpy.Stdlib/spy/heapq.spy from the section: red (1 failed, 60 passed: "heapq.spy: holds CPython docstring text ... but is not under 'Sharpy files holding these summaries:'"); (b) bisect_module.spy's module docstring replaced by bisect.insort's "Insert item x in list a, and keep it sorted assuming a is sorted.": red (1 failed, 60 passed: "bisect_module.spy: holds CPython docstring text ... <- Lib/bisect.py"); each restored with cp + cmp: green (61 passed). Refs #2602 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- THIRD-PARTY-NOTICES.txt | 47 ++++ build_tools/tests/test_third_party_notices.py | 232 +++++++++++++++++- 2 files changed, 275 insertions(+), 4 deletions(-) diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index d8d0dffc47..19b42a7ab3 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -325,6 +325,53 @@ carries the .spy file's notice. There is no copy_function, symlink or ignore handling, and errors are raised as Sharpy's OSError family. +API documentation summaries adapted from CPython docstrings +----------------------------------------------------------- + +Some one-line API summaries in the files below (a .spy docstring, or a C# +) are sentences taken from the docstrings of CPython's standard +library, Lib/ in CPython 3.15 (compared against 3.15.2). Only those +summaries are derived from CPython: unless a file is also listed above, +its code is Sharpy's own and it carries no PSF header. The summaries are +used under the PSF License Version 2, whose text follows this section. A +.spy file stands for itself and the C# generated from it. + +Sharpy files holding these summaries: + + src/Sharpy.Core/Partial.Dict/Dict.Methods.cs + src/Sharpy.Stdlib/Datetime/Datetime.cs + src/Sharpy.Stdlib/Heapq/Heapq.Merge.cs + src/Sharpy.Stdlib/Logging/LoggingModule.cs + src/Sharpy.Stdlib/Pathlib/Path.cs + src/Sharpy.Stdlib/Pathlib/__Init__.cs + src/Sharpy.Stdlib/spy/calendar_module.spy + src/Sharpy.Stdlib/spy/fnmatch_module.spy + src/Sharpy.Stdlib/spy/heapq.spy + src/Sharpy.Stdlib/spy/logging_module.spy + src/Sharpy.Stdlib/spy/os_path_module.spy + src/Sharpy.Stdlib/spy/pathlib_module.spy + src/Sharpy.Stdlib/spy/pprint_module.spy + src/Sharpy.Stdlib/spy/shutil_module.spy + src/Sharpy.Stdlib/spy/statistics.spy + src/Sharpy.Stdlib/spy/subprocess_module.spy + src/Sharpy.Stdlib/spy/textwrap.spy + +Upstream source: CPython 3.15, the docstrings of Lib/calendar.py, +collections/__init__.py, fnmatch.py, genericpath.py, heapq.py, +logging/__init__.py, ntpath.py, pathlib/__init__.py, pathlib/types.py, +pprint.py, _pydatetime.py, shutil.py, statistics.py, subprocess.py and +textwrap.py. + +Summary of changes: each sentence documents the Sharpy API of the same +name. It may differ from its CPython docstring in letter case, line +wrapping and a final full stop; the rest of each Sharpy docstring is +Sharpy's own. The list above is the set of files in which +build_tools/tests/test_third_party_notices.py finds a summary whose first +paragraph (for a C# summary, its whole text or its first sentence) +equals, ignoring letter case, whitespace and a final full stop, the first +paragraph of a docstring in CPython 3.15's Lib/ that is longer than 30 +characters (Lib's test packages, idlelib and site-packages are not read). + The CPython license text follows, verbatim from the LICENSE.txt shipped with CPython 3.15.2 (lib/python3.15/LICENSE.txt). It is the complete file. diff --git a/build_tools/tests/test_third_party_notices.py b/build_tools/tests/test_third_party_notices.py index 67fae0c9f9..58ae595848 100644 --- a/build_tools/tests/test_third_party_notices.py +++ b/build_tools/tests/test_third_party_notices.py @@ -19,7 +19,9 @@ namesake: its keys are exactly the namesake modules on disk (a new module is red until someone reads it against its CPython source and records a verdict), the files in a ``port`` module that carry the header are exactly the files its row names (a lost header and an extra one are both red), and a - ``behaviour`` module has none. + ``behaviour`` module has none; +* the files the notices list under "Sharpy files holding these summaries:" are exactly the files + whose API summaries repeat a CPython 3.15 Lib docstring (documentation, so no PSF header). The claim scan only catches files that declare themselves ports; a port that makes no such claim (a structural port with no comment saying so) is caught by the census, which forces a reading of each new @@ -102,10 +104,12 @@ def _has_header(text: str) -> bool: return all(line in text for line in HEADER_LINES) -def listed_files(notices: str) -> Set[str]: - """The paths under 'Sharpy files derived from it:' (one per 4-space-indented line).""" +def listed_files( + notices: str, label: str = "Sharpy files derived from it:" +) -> Set[str]: + """The paths under the first `label` line (one per 4-space-indented line).""" lines = notices.splitlines() - start = lines.index("Sharpy files derived from it:") + start = lines.index(label) listed: Set[str] = set() for line in lines[start + 1 :]: if not line.strip(): @@ -626,3 +630,223 @@ def test_census_names_a_malformed_row(tmp_path: Path, row): assert ( len(problems) == 1 and "is not (verdict, set of file paths)" in problems[0] ), problems + + +# ---- API summaries adapted from CPython docstrings (#2602 follow-up, owner 2026-11-20) ---- +# +# Some one-line API summaries (a .spy docstring, a C# ) are CPython Lib docstrings copied +# word for word. That is documentation, not code: the files keep no PSF header (a "behaviour" census +# row stays header-free), and THIRD-PARTY-NOTICES.txt credits them in one section whose file list +# must equal the set this matcher finds. The rule is the #2777 review's: a summary matches when its +# first paragraph (a C# summary: the whole text or its first sentence), whitespace collapsed, case +# and a final full stop ignored, equals the first paragraph of a docstring (module, class or +# function) in CPython's Lib that is longer than DOCSTRING_MIN characters. Lib's test packages, +# idlelib and site-packages are not read. C# generated from a .spy file is skipped: the .spy file is +# listed for it, as the notices file says. + +DOCSTRING_LABEL = "Sharpy files holding these summaries:" +DOCSTRING_MIN = 30 +DOCSTRING_ORACLE = (3, 15) + +# Run under the oracle's python (`-I`): prints {"version": ..., "index": {key: Lib-relative path}}. +# argv[1], when given, is the Lib directory to read instead of the interpreter's own. +_INDEX_SCRIPT = r""" +import ast, json, os, sys +lib = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.__file__) +index = {} +for dirpath, dirnames, filenames in os.walk(lib): + dirnames.sort() + for name in sorted(filenames): + if not name.endswith(".py"): + continue + path = os.path.join(dirpath, name) + rel = os.path.relpath(path, lib).replace(os.sep, "/") + if "/test" in "/" + rel or "site-packages" in rel or "idlelib" in rel: + continue + try: + with open(path, encoding="utf-8") as f: + tree = ast.parse(f.read()) + except Exception: + continue + for node in ast.walk(tree): + if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + doc = ast.get_docstring(node) + if doc: + first = " ".join(doc.strip().split("\n\n")[0].split()) + if len(first) > MIN: + index.setdefault(first.rstrip(".").lower(), rel) +print(json.dumps({"version": list(sys.version_info[:3]), "index": index})) +""".replace("MIN", str(DOCSTRING_MIN)) + +_SPY_DOCSTRING = re.compile(r'"""(.*?)"""', re.S) +_CS_SUMMARY = re.compile(r"(.*?)", re.S) +_GENERATED = "// Generated from" + + +def _key(text: str) -> str: + return " ".join(text.strip().split("\n\n")[0].split()).rstrip(".").lower() + + +def summary_keys(path: Path, text: str) -> List[str]: + """The match keys of a file's summaries (a C# summary gives its whole text and first sentence).""" + if path.suffix == ".spy": + return [_key(m.group(1)) for m in _SPY_DOCSTRING.finditer(text)] + if text.startswith(_GENERATED): + return [] + keys = [] + for m in _CS_SUMMARY.finditer(text): + summary = re.sub(r"<[^>]+>", "", re.sub(r"\s*///\s*", " ", m.group(1))) + whole = " ".join(summary.split()).rstrip(".").lower() + keys += [whole, whole.split(". ")[0]] + return keys + + +def docstring_matches(root: Path, index: Dict[str, str]) -> Dict[str, List[str]]: + """Root-relative path -> 'summary <- Lib path' for each summary found in the CPython index.""" + found: Dict[str, List[str]] = {} + for path in sources(root): + hits = sorted( + { + f"{key!r} <- Lib/{index[key]}" + for key in summary_keys(path, path.read_text(encoding="utf-8")) + if key in index + } + ) + if hits: + found[path.relative_to(root).as_posix()] = hits + return found + + +def docstring_problems(listed: Set[str], found: Dict[str, List[str]]) -> List[str]: + problems = [ + f"{rel}: holds CPython docstring text ({found[rel][0]}) but is not under " + f"{DOCSTRING_LABEL!r} in THIRD-PARTY-NOTICES.txt" + for rel in sorted(set(found) - listed) + ] + problems += [ + f"{rel}: under {DOCSTRING_LABEL!r} in THIRD-PARTY-NOTICES.txt but holds no CPython " + "docstring text; delete the line" + for rel in sorted(listed - set(found)) + ] + return problems + + +def _run_index(python: str, lib: str = "") -> Dict[str, object]: + import json + import subprocess + + argv = [python, "-I", "-c", _INDEX_SCRIPT] + ([lib] if lib else []) + out = subprocess.run(argv, check=True, capture_output=True, text=True).stdout + return json.loads(out) + + +@pytest.fixture(scope="module") +def cpython_docstrings() -> Dict[str, str]: + import shutil + + if sys.version_info[:2] == DOCSTRING_ORACLE: + python = sys.executable + else: + python = shutil.which("python%d.%d" % DOCSTRING_ORACLE) or "" + if not python: + pytest.skip( + "the docstring oracle is CPython %d.%d's Lib (.python-version); " + "python%d.%d is not on PATH" % (DOCSTRING_ORACLE * 2) + ) + result = _run_index(python) + assert tuple(result["version"][:2]) == DOCSTRING_ORACLE, result["version"] + return result["index"] + + +def test_docstring_matcher_sees_the_known_summaries(cpython_docstrings): + # Positive control: an empty result elsewhere means "none", not "looked nowhere". + assert cpython_docstrings.get( + "push item onto heap, maintaining the heap invariant" + ) == ("heapq.py") + found = docstring_matches(REPO, cpython_docstrings) + assert { + "src/Sharpy.Stdlib/spy/heapq.spy", + "src/Sharpy.Stdlib/Pathlib/Path.cs", + } <= set(found), sorted(found) + + +def test_docstring_notice_lists_exactly_the_files_holding_cpython_docstrings( + cpython_docstrings, +): + notices = NOTICES.read_text(encoding="utf-8") + listed = listed_files(notices, DOCSTRING_LABEL) + found = docstring_matches(REPO, cpython_docstrings) + problems = docstring_problems(listed, found) + assert not problems, "\n".join(problems) + + +def test_docstring_index_reads_first_paragraphs_over_the_minimum(tmp_path: Path): + # The index rule, run by this interpreter over a stand-in Lib (no oracle needed). + long = "Return the frobnicated value of the given widget." + (tmp_path / "frob.py").write_text( + f'"""Frobnication helpers for widgets and gadgets.\n\nMore text."""\n' + f'def frob(x):\n """{long}\n\n Details."""\n' + 'def short(x):\n """Return x unchanged here."""\n', + encoding="utf-8", + ) + (tmp_path / "test").mkdir() + (tmp_path / "test" / "test_frob.py").write_text( + '"""A test module docstring that is long enough."""\n', encoding="utf-8" + ) + index = _run_index(sys.executable, str(tmp_path))["index"] + assert index == { + "frobnication helpers for widgets and gadgets": "frob.py", + long.rstrip(".").lower(): "frob.py", + } + + +_FAKE_INDEX = {"return the frobnicated value of the given widget": "frob.py"} + + +def _source(tmp_path: Path, rel: str, text: str) -> None: + path = tmp_path / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +@pytest.mark.parametrize( + "rel, text", + [ + ( + "src/Sharpy.Stdlib/spy/frob.spy", + 'def frob(x: int) -> int:\n """Return the frobnicated value of the\n' + ' given widget.\n\n Sharpy details."""\n', + ), + ( + "src/Sharpy.Stdlib/Frob/Frob.cs", + "/// \n/// Return the frobnicated value of the given widget.\n/// \n", + ), + ( + "src/Sharpy.Core/Frob.cs", + "/// Return the frobnicated value of the given widget. Sharpy adds more." + "\n", + ), + ], +) +def test_docstring_check_refuses_an_unlisted_copy(tmp_path: Path, rel: str, text: str): + _source(tmp_path, rel, text) + found = docstring_matches(tmp_path, _FAKE_INDEX) + assert set(found) == {rel}, found + problems = docstring_problems(set(), found) + assert len(problems) == 1 and "is not under" in problems[0], problems + assert docstring_problems({rel}, found) == [] + + +def test_docstring_check_refuses_a_stale_line_and_skips_generated_csharp( + tmp_path: Path, +): + _source( + tmp_path, + "src/Sharpy.Stdlib/Frob/Frob.cs", + _GENERATED + " src/Sharpy.Stdlib/spy/frob.spy\n" + "/// Return the frobnicated value of the given widget.\n", + ) + found = docstring_matches(tmp_path, _FAKE_INDEX) + assert found == {} + problems = docstring_problems({"src/Sharpy.Stdlib/Frob/Frob.cs"}, found) + assert len(problems) == 1 and "delete the line" in problems[0], problems From 813d1412d9bfc43831aaba45995ca34b0e899501 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 21:01:48 +0000 Subject: [PATCH 3/6] build: credit Unicode case folding and PyYAML regexes in the notices The #2777 review found two derived pieces from non-CPython sources: - src/Sharpy.Core/StringExtensions.Format.cs: the case-folding table (s_caseFoldTable) and the Cherokee ranges in CaseFoldChar, from the Unicode Character Database's CaseFolding.txt. The source records no version; all 125 entries equal CPython 3.15.2's str.casefold, which uses Unicode 17.0.0. - src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs: Yaml11Int and Yaml11Float, transcribed from PyYAML 6.0.3's implicit resolvers (lib/yaml/resolver.py; checked against the 6.0.3 tag's file). THIRD-PARTY-NOTICES.txt gains a section for each (upstream, version, derived portion, full licence text), placed before the CPython section so the CPython licence stays the file's last 277 lines. Each file gains a short header naming its upstream and pointing at the notices. The intro now says the #2602 audit covered CPython, names these two sources as also listed, and claims no other completeness. Licence texts, fetched 2026-11-20: - PyYAML: https://raw.githubusercontent.com/yaml/pyyaml/6.0.3/LICENSE (sha256 8d3928f9...a577e8a4), verbatim. - Unicode License V3: https://www.unicode.org/license.txt was refused by the network proxy (403); the text is the first section of https://raw.githubusercontent.com/unicode-org/icu/main/LICENSE (the Unicode Consortium's repository), verbatim, and differs from SPDX's Unicode-3.0 text (spdx/license-list-data) only in the copyright years (1991-2026 against 1991-2023). No PackageLicenseExpression changes (the owner's call). Refs #2602 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- THIRD-PARTY-NOTICES.txt | 137 +++++++++++++++++-- src/Sharpy.Core/StringExtensions.Format.cs | 3 + src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs | 3 + 3 files changed, 135 insertions(+), 8 deletions(-) diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 19b42a7ab3..682cbe7c72 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -3,15 +3,136 @@ THIRD-PARTY NOTICES Sharpy is dual-licensed under the Apache License, Version 2.0 and the MIT License (see LICENSE, LICENSE-APACHE and LICENSE-MIT). Some files in this -repository contain code derived from third-party software that is distributed -under its own license. A component listed below is given with the Sharpy -files derived from it, the upstream source, and the full license text under -which it is used. The CPython list is the result of the audit in issue #2602 -of the Sharpy repository, which read every Sharpy.Stdlib module that has a -CPython namesake, and the Sharpy.Core files that follow CPython's +repository contain code or data derived from third-party software that is +distributed under its own license. A component listed below is given with +the Sharpy files derived from it, the upstream source, and the full license +text under which it is used. The CPython list is the result of the audit in +issue #2602 of the Sharpy repository, which read every Sharpy.Stdlib module +that has a CPython namesake, and the Sharpy.Core files that follow CPython's implementation, against their CPython sources. That audit covered CPython -only: code or data derived from other upstream sources was outside its -scope, and this file does not claim to list it. +only. Two other upstream sources, found in the review of that audit, are +also listed: the Unicode Character Database (a case-folding table in +Sharpy.Core) and PyYAML (two regular expressions in Sharpy.Stdlib's YAML +module). No other source was audited, and this file does not claim to list +every piece of code or data derived from a source other than CPython. + + +Unicode Character Database +========================== + +Copyright © 1991-2026 Unicode, Inc. + +Sharpy file derived from it: + + src/Sharpy.Core/StringExtensions.Format.cs (only the case-folding + data: the table s_caseFoldTable and the Cherokee ranges in + CaseFoldChar) + +Upstream source: the Unicode Character Database, CaseFolding.txt +(https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt). The file +does not record which Unicode version the table was taken from; every +entry in it equals the full case folding of CPython 3.15.2's +str.casefold, which uses Unicode 17.0.0. + +Derived portion: the full case foldings (status C and F) that differ from +.NET's char.ToLowerInvariant, written as a C# dictionary, and the +Cherokee mappings written as range checks. + +The Unicode License V3 (SPDX Unicode-3.0; https://www.unicode.org/license.txt) +follows, verbatim from the first section of the LICENSE file in the +Unicode Consortium's ICU repository +(https://github.com/unicode-org/icu/blob/main/LICENSE, November 2026). +Apart from its copyright years it is word for word the Unicode-3.0 text +of the SPDX License List. + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + + +PyYAML +====== + +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +Sharpy file derived from it: + + src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs (only the regular + expressions Yaml11Int and Yaml11Float) + +Upstream source: PyYAML 6.0.3, lib/yaml/resolver.py +(https://github.com/yaml/pyyaml) + +Derived portion: Yaml11Int is the expression of the implicit resolver +for tag:yaml.org,2002:int, with its binary, octal, decimal and +hexadecimal arms (hexadecimal moved before octal) and without its +sexagesimal arm. Yaml11Float is the first two arms of the resolver for +tag:yaml.org,2002:float (digits with a required dot, and a leading dot), +without its sexagesimal, .inf and .nan arms. Both were rewritten as .NET +regular expressions, with a non-capturing group dropped and no other +change to what they match within those arms. + +The PyYAML license text follows, verbatim from the LICENSE file at +PyYAML's 6.0.3 tag +(https://raw.githubusercontent.com/yaml/pyyaml/6.0.3/LICENSE). + +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. CPython diff --git a/src/Sharpy.Core/StringExtensions.Format.cs b/src/Sharpy.Core/StringExtensions.Format.cs index d54edc3d66..07c1826c4a 100644 --- a/src/Sharpy.Core/StringExtensions.Format.cs +++ b/src/Sharpy.Core/StringExtensions.Format.cs @@ -1,3 +1,6 @@ +// The case-folding data in this file (s_caseFoldTable and the Cherokee ranges in CaseFoldChar) is +// derived from the Unicode Character Database's CaseFolding.txt, Copyright (c) 1991-2026 Unicode, Inc., +// used under the Unicode License V3 (SPDX Unicode-3.0); see THIRD-PARTY-NOTICES.txt. using System; using System.Collections; using System.Collections.Generic; diff --git a/src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs b/src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs index 3ec2716e4d..87144f6dd2 100644 --- a/src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs +++ b/src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs @@ -1,3 +1,6 @@ +// The regular expressions Yaml11Int and Yaml11Float are transcribed from PyYAML 6.0.3's implicit +// resolvers (lib/yaml/resolver.py), Copyright (c) 2017-2021 Ingy döt Net and Copyright (c) 2006-2016 +// Kirill Simonov, used under the MIT License; see THIRD-PARTY-NOTICES.txt. using System; using System.Globalization; using System.Text.RegularExpressions; From 0288f70ae92b5f6873778a656df3ea1a22c89296 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 21:33:33 +0000 Subject: [PATCH 4/6] build: declare Unicode-3.0 and PyYAML's MIT in the package licences Owner ruling, 2026-11-20. Asked: "should the published NuGet packages' licence declarations name these two new sources? I'd add them: Core: add `Unicode-3.0`... Stdlib: add `MIT` for PyYAML... The `sharpyc` package: add both". Answer, verbatim: "yes". - SharpyLang.Core: (Apache-2.0 OR MIT) AND Python-2.0 AND Unicode-3.0 - SharpyLang.Stdlib: (Apache-2.0 OR MIT) AND Python-2.0 AND MIT - sharpyc: (Apache-2.0 OR MIT) AND Python-2.0 AND Unicode-3.0 AND MIT A local pack of sharpyc carries tools/net10.0/any/Sharpy.Core.dll and Sharpy.Stdlib.dll (and no per-module Stdlib DLL), so it needs both. NuGet accepts the repeated MIT: `dotnet-serialized pack src/Sharpy.Stdlib` and `pack src/Sharpy.Cli` succeed with no warning, and each nuspec keeps the expression as written ((Apache-2.0 OR MIT) AND Python-2.0 AND MIT; the sharpyc one names Unicode-3.0 too), so the parser neither refuses nor normalises it. Unicode-3.0 joins NUGET_ACCEPTED: isOsiApproved true (isFsfLibre unset) in spdx/license-list-data json/licenses.json, read 2026-11-20. The README test pinned only ids the package expressions add to the project default, so PyYAML's MIT (already in `Apache-2.0 OR MIT`) was invisible to it. test_package_licenses.py now pins each expression whole (PACKAGE_EXPRESSIONS), and README.md's notices line must give each package exactly the AND-terms its expression adds after (Apache-2.0 OR MIT), checked per package segment. The README line now names what each package ships. Mutations (each restored with cp + cmp; green after: 16 passed): | mutation | result | |--------------------------------------------|-------------------------| | Core drops `AND Unicode-3.0` | red: 2 failed/14 passed | | | (ruled expression, | | | README per package) | | Stdlib drops `AND MIT` (PyYAML) | red: 2 failed/14 passed | | README drops Core's `Unicode-3.0` | red: 1 failed/15 passed | | | ("`SharpyLang.Core` is | | | given ['Python-2.0']") | | README drops Stdlib's `MIT` | red: 1 failed/15 passed | Gate: pytest build_tools/tests 2262 passed / 0 failed / 0 skipped; scorecard_metrics --check OK; Release packs of Stdlib and Cli built clean. Refs #2602 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- README.md | 2 +- build_tools/tests/test_package_licenses.py | 124 +++++++++++++++++---- src/Sharpy.Cli/Sharpy.Cli.csproj | 4 +- src/Sharpy.Core/Sharpy.Core.csproj | 4 +- src/Sharpy.Stdlib/Sharpy.Stdlib.csproj | 4 +- 5 files changed, 112 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 4db3fb6265..8d04a23bed 100644 --- a/README.md +++ b/README.md @@ -80,4 +80,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project shall be dual licensed as above, without any additional terms or conditions. -Sharpy is Apache-2.0 OR MIT; portions ported from CPython are under the CPython licence (SPDX `Python-2.0`), see [THIRD-PARTY-NOTICES.txt](THIRD-PARTY-NOTICES.txt). +Sharpy is Apache-2.0 OR MIT. Some packages also ship third-party code or data, credited with its licence text in [THIRD-PARTY-NOTICES.txt](THIRD-PARTY-NOTICES.txt), and their licence expressions add those licences (SPDX ids): `SharpyLang.Core` adds `Python-2.0` (CPython ports) and `Unicode-3.0` (Unicode case-folding data); `SharpyLang.Stdlib` adds `Python-2.0` (CPython ports) and `MIT` (PyYAML's resolver patterns); `sharpyc`, which ships both libraries, adds `Python-2.0`, `Unicode-3.0` and `MIT`. diff --git a/build_tools/tests/test_package_licenses.py b/build_tools/tests/test_package_licenses.py index 843ba8d5bc..fc1ea30d8a 100644 --- a/build_tools/tests/test_package_licenses.py +++ b/build_tools/tests/test_package_licenses.py @@ -16,8 +16,9 @@ REPO = Path(__file__).resolve().parent.parent.parent # SPDX ids checked against https://spdx.org/licenses/ (isOsiApproved or isFsfLibre true). -# Add an id only after checking that list; nuget.org refuses the rest. -NUGET_ACCEPTED = {"Apache-2.0", "MIT", "Python-2.0"} +# Add an id only after checking that list; nuget.org refuses the rest. Unicode-3.0: isOsiApproved +# true (isFsfLibre unset) in spdx/license-list-data json/licenses.json, read 2026-11-20. +NUGET_ACCEPTED = {"Apache-2.0", "MIT", "Python-2.0", "Unicode-3.0"} _EXPR = re.compile( r"]*>([^<]*)" @@ -123,31 +124,116 @@ def _tracked_text_files() -> dict[str, str]: return texts -def _third_party_ids() -> set[str]: - """Ids a packaged expression adds to the project's own default (Directory.Build.props).""" - exprs = _expressions() - default = {i for f, e in exprs if f == "Directory.Build.props" for i in _ids(e)} - return {i for _, e in exprs for i in _ids(e)} - default +# Each package declares the licences of the third-party code it ships (THIRD-PARTY-NOTICES.txt): +# CPython ports (Python-2.0) in Core and Stdlib, Unicode case-folding data (Unicode-3.0) in Core, +# PyYAML's resolver regexes (MIT) in Stdlib, and all three in sharpyc, which ships Sharpy.Core.dll +# and Sharpy.Stdlib.dll. Owner, 2026-11-20, asked whether to add Unicode-3.0 to Core, MIT to Stdlib +# and both to sharpyc: "yes". PyYAML's MIT is a term of its own, ANDed on: it is not the MIT of +# Sharpy's `Apache-2.0 OR MIT`, so an id-set comparison against the default cannot see it, and the +# expressions are pinned whole. A change here is a change to what ships, read against the notices. +OWN_LICENCE = "(Apache-2.0 OR MIT)" +PACKAGE_EXPRESSIONS = { + "Directory.Build.props": "Apache-2.0 OR MIT", + "src/Sharpy.Core/Sharpy.Core.csproj": "(Apache-2.0 OR MIT) AND Python-2.0 AND Unicode-3.0", + "src/Sharpy.Stdlib/Sharpy.Stdlib.csproj": "(Apache-2.0 OR MIT) AND Python-2.0 AND MIT", + "src/Sharpy.Cli/Sharpy.Cli.csproj": ( + "(Apache-2.0 OR MIT) AND Python-2.0 AND Unicode-3.0 AND MIT" + ), +} -def test_the_readme_names_the_licence_the_packages_declare(): - ids = _third_party_ids() - assert ids == {"Python-2.0"}, ( - f"third-party ids in the package expressions: {sorted(ids)}; " - "a new one is named in README.md's notices line, then added here" +def test_each_package_declares_the_ruled_expression(): + found: dict[str, list[str]] = {} + for f, expr in _expressions(): + found.setdefault(f, []).append(" ".join(expr.split())) + expected = {f: [e] for f, e in PACKAGE_EXPRESSIONS.items()} + assert found == expected, ( + "PackageLicenseExpression differs from the owner's ruling; change what ships " + "and THIRD-PARTY-NOTICES.txt together, then PACKAGE_EXPRESSIONS" ) + + +def third_party_terms(expression: str) -> list[str]: + """The AND-terms a package adds to Sharpy's own `(Apache-2.0 OR MIT)`, in order.""" + terms = [t.strip() for t in " ".join(expression.split()).split(" AND ")] + return [t for t in terms if t != OWN_LICENCE] + + +def _package_ids() -> dict[str, str]: + """Project file -> PackageId, for the projects that override the licence expression.""" + ids = {} + for f in PACKAGE_EXPRESSIONS: + m = re.search( + r"([^<]+)", + (REPO / f).read_text(encoding="utf-8"), + ) + if m: + ids[f] = m.group(1).strip() + return ids + + +def readme_problems(line: str, packages: dict[str, list[str]]) -> list[str]: + """`packages` maps a PackageId to its third-party ids. In the README line, each package's + segment (from its backticked id to the next package's) names exactly its ids, backticked.""" + starts = sorted( + (line.find(f"`{pkg}`"), pkg) for pkg in packages if f"`{pkg}`" in line + ) + problems = [ + f"the line does not name the package `{pkg}`" + for pkg in sorted(packages) + if f"`{pkg}`" not in line + ] + known = NUGET_ACCEPTED | {i for ids in packages.values() for i in ids} + for n, (pos, pkg) in enumerate(starts): + end = starts[n + 1][0] if n + 1 < len(starts) else len(line) + named = set(re.findall(r"`([^`]+)`", line[pos:end])) & known + if named != set(packages[pkg]): + problems.append( + f"`{pkg}` is given {sorted(named)}, but its expression adds " + f"{sorted(packages[pkg])}" + ) + return problems + + +def _readme_line() -> str: readme = (REPO / "README.md").read_text(encoding="utf-8") - # The id must sit on the line that states what the CPython ports are under. - claims = [ + lines = [ line for line in readme.splitlines() - if "CPython" in line and "THIRD-PARTY-NOTICES.txt" in line + if "THIRD-PARTY-NOTICES.txt" in line and "`sharpyc`" in line ] - assert claims, "README.md has no line naming CPython and THIRD-PARTY-NOTICES.txt" - bad = [line for line in claims for i in sorted(ids) if f"`{i}`" not in line] - assert not bad, ( - f"README.md's CPython licence line does not name {sorted(ids)}: {bad}" + assert len(lines) == 1, ( + "README.md has no single line naming THIRD-PARTY-NOTICES.txt and the packages" ) + return lines[0] + + +def test_the_readme_names_the_licences_each_package_declares(): + exprs = dict(_expressions()) + package_ids = _package_ids() + assert set(package_ids) == set(PACKAGE_EXPRESSIONS) - {"Directory.Build.props"} + packages = { + package_ids[f]: third_party_terms(exprs[f]) for f in package_ids if f in exprs + } + problems = readme_problems(_readme_line(), packages) + assert not problems, "README.md's notices line:\n" + "\n".join(problems) + + +def test_the_readme_check_refuses_a_missing_or_extra_id(): + packages = {"Core": ["Python-2.0", "Unicode-3.0"], "Stdlib": ["Python-2.0", "MIT"]} + good = "Apache-2.0 OR MIT; `Core` adds `Python-2.0` and `Unicode-3.0`; `Stdlib` adds `Python-2.0` and `MIT`." + assert readme_problems(good, packages) == [] + for bad in ( + good.replace(" and `MIT`", ""), # PyYAML's MIT missing from Stdlib + good.replace(" and `Unicode-3.0`", ""), + good.replace("`Core` adds", "`Core` adds `MIT`,"), + good.replace("; `Stdlib` adds `Python-2.0` and `MIT`", ""), + ): + assert readme_problems(bad, packages), bad + assert third_party_terms("(Apache-2.0 OR MIT) AND Python-2.0 AND MIT") == [ + "Python-2.0", + "MIT", + ] def test_no_file_names_the_retired_cpython_licence_id(): diff --git a/src/Sharpy.Cli/Sharpy.Cli.csproj b/src/Sharpy.Cli/Sharpy.Cli.csproj index 7563db16aa..4aa54d2c05 100644 --- a/src/Sharpy.Cli/Sharpy.Cli.csproj +++ b/src/Sharpy.Cli/Sharpy.Cli.csproj @@ -12,8 +12,8 @@ sharpyc Sharpy compiler — a statically-typed Pythonic language for .NET. Compile .spy files to C# and run them on the CLR. README.md - - (Apache-2.0 OR MIT) AND Python-2.0 + + (Apache-2.0 OR MIT) AND Python-2.0 AND Unicode-3.0 AND MIT diff --git a/src/Sharpy.Core/Sharpy.Core.csproj b/src/Sharpy.Core/Sharpy.Core.csproj index 4285bf90a7..7ea9e65469 100644 --- a/src/Sharpy.Core/Sharpy.Core.csproj +++ b/src/Sharpy.Core/Sharpy.Core.csproj @@ -13,8 +13,8 @@ true Runtime library for the Sharpy programming language. Provides Pythonic collection types (List, Dict, Set), Optional, Result, and built-in functions for .NET. README.md - - (Apache-2.0 OR MIT) AND Python-2.0 + + (Apache-2.0 OR MIT) AND Python-2.0 AND Unicode-3.0 diff --git a/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj b/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj index 3c35c58b23..250c006727 100644 --- a/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj +++ b/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj @@ -13,8 +13,8 @@ true Standard library for the Sharpy programming language. Provides json, os, re, math, and 60+ modules with Pythonic APIs on .NET. README.md - - (Apache-2.0 OR MIT) AND Python-2.0 + + (Apache-2.0 OR MIT) AND Python-2.0 AND MIT CS1574;CS1580;CS1591 From 978124ccb42a1c5949d4987dbc58b404d529baed Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 21:47:29 +0000 Subject: [PATCH 5/6] build: widen the docstring guard, credit YamlScalarStyle as PyYAML Fixes the #2780 independent review of 813d1412d ("merge after fixes"). 1. C-implemented docstrings. The index now also reads the __doc__ of every module in sys.builtin_module_names and lib-dynload (test modules aside), of their functions and classes, and of the classes' methods and descriptors. math_module.spy (math.cosh, math.isnan, ...) and the Core/itertools/os/collections files the reviewer found are now matched and listed. 2. Wider matching. Both sides key every paragraph and every sentence (split at . ! ? before a capital), with * and ` markup removed, so a later paragraph's sentence (os.makedirs' "Super-mkdir; ...") and reST-marked text (shlex, glob, secrets) match. The floor is at least 30 characters after a final full stop is dropped (the old "longer than 30 with its full stop", which keeps Path.cs's "The logical parent of the path."). The notices now say verbatim sentences are credited; paraphrases and Doc/*.rst text are not matched, audited or listed. Of the reviewer's named cases, OrderedDict.cs, HtmlFunctions.cs, PlatformModule.cs and bisect_module.spy have no verbatim sentence and stay unlisted (difflib_module.spy's lines are paraphrases too); ChainMap.cs has one and is listed. The section's per-file "Upstream source" list was unguarded and is dropped. The list is the matcher's output exactly: 36 files. 3. Oracle. The CPython minor is read from .python-version. Without that interpreter the guard skips locally and fails when CI is set. A fake-environment unit test pins run/skip/fail, and the section must name the oracle minor. 4. src/Sharpy.Stdlib/Yaml/YamlScalarStyle.cs ports PyYAML's Emitter.analyze_scalar and choose_scalar_style. It is listed in the PyYAML section (lib/yaml/emitter.py, portion and drops described) and carries the PyYAML header. YamlControlEscapes and YamlFloatFormat are not derived. 5. Labels. listed_files reads the CPython list from the CPython heading, the Unicode and PyYAML sections use "Sharpy files derived from this source:", and a new guard requires those lists to equal the files whose header points at THIRD-PARTY-NOTICES.txt without PSF lines. Mutations (each restored with cp, checked with cmp: all "cmp ok"): | # | mutation | result | |---|-------------------------------------------------|-----------------| | 1a| reviewer's len.__doc__ into Len.cs's | red 1/73 | | 1b| index script: runtime = False | red 3/71 | | 2a| os.makedirs 2nd-paragraph sentence into | red 1/73 | | | bisect_module.spy | | | 2b| "Serialize obj to a JSON formatted str." (json. | red 1/73 | | | dumps, markup stripped) into bisect_module.spy | | | 2c| doc_keys without per-sentence keys | red 4/70 | | 2d| doc_keys without * and ` stripping | red 3/71 | | 3a| resolve_oracle returns "skip" on CI too | red 1/73 | | 3b| .python-version -> 3.16, CI=true | red: 2 errors | | | (without CI: the two oracle tests skip) | + 1 failed | | 4a| YamlScalarStyle.cs dropped from the PyYAML list | red 1/73 | | 4b| YamlScalarStyle.cs header dropped | red 1/73 | | 5a| listed_files searches from the top | red 1/73 | | 5b| PyYAML section takes the CPython label | red 2/72 | (n/m = failed/passed in test_third_party_notices.py; green: 74 passed. In 3b the 1 failure is the section-names-the-oracle pin, which fails with or without CI.) Gate: pytest build_tools/tests (python3.15) 2275 passed / 0 failed / 0 skipped; build sharpy.sln 0 warnings 0 errors; format whitespace --verify-no-changes clean; scorecard_metrics --check OK. No .spy content changed. Refs #2602 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- README.md | 2 +- THIRD-PARTY-NOTICES.txt | 99 ++-- build_tools/tests/test_third_party_notices.py | 429 +++++++++++++++--- src/Sharpy.Cli/Sharpy.Cli.csproj | 2 +- src/Sharpy.Stdlib/Sharpy.Stdlib.csproj | 2 +- src/Sharpy.Stdlib/Yaml/YamlScalarStyle.cs | 3 + 6 files changed, 438 insertions(+), 99 deletions(-) diff --git a/README.md b/README.md index 8d04a23bed..7f49c74678 100644 --- a/README.md +++ b/README.md @@ -80,4 +80,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project shall be dual licensed as above, without any additional terms or conditions. -Sharpy is Apache-2.0 OR MIT. Some packages also ship third-party code or data, credited with its licence text in [THIRD-PARTY-NOTICES.txt](THIRD-PARTY-NOTICES.txt), and their licence expressions add those licences (SPDX ids): `SharpyLang.Core` adds `Python-2.0` (CPython ports) and `Unicode-3.0` (Unicode case-folding data); `SharpyLang.Stdlib` adds `Python-2.0` (CPython ports) and `MIT` (PyYAML's resolver patterns); `sharpyc`, which ships both libraries, adds `Python-2.0`, `Unicode-3.0` and `MIT`. +Sharpy is Apache-2.0 OR MIT. Some packages also ship third-party code or data, credited with its licence text in [THIRD-PARTY-NOTICES.txt](THIRD-PARTY-NOTICES.txt), and their licence expressions add those licences (SPDX ids): `SharpyLang.Core` adds `Python-2.0` (CPython ports) and `Unicode-3.0` (Unicode case-folding data); `SharpyLang.Stdlib` adds `Python-2.0` (CPython ports) and `MIT` (PyYAML's resolver patterns and scalar-style rules); `sharpyc`, which ships both libraries, adds `Python-2.0`, `Unicode-3.0` and `MIT`. diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 682cbe7c72..842adc28fe 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -22,7 +22,7 @@ Unicode Character Database Copyright © 1991-2026 Unicode, Inc. -Sharpy file derived from it: +Sharpy files derived from this source: src/Sharpy.Core/StringExtensions.Format.cs (only the case-folding data: the table s_caseFoldTable and the Cherokee ranges in @@ -92,22 +92,37 @@ PyYAML Copyright (c) 2017-2021 Ingy döt Net Copyright (c) 2006-2016 Kirill Simonov -Sharpy file derived from it: +Sharpy files derived from this source: src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs (only the regular expressions Yaml11Int and Yaml11Float) - -Upstream source: PyYAML 6.0.3, lib/yaml/resolver.py -(https://github.com/yaml/pyyaml) - -Derived portion: Yaml11Int is the expression of the implicit resolver -for tag:yaml.org,2002:int, with its binary, octal, decimal and -hexadecimal arms (hexadecimal moved before octal) and without its -sexagesimal arm. Yaml11Float is the first two arms of the resolver for -tag:yaml.org,2002:float (digits with a required dot, and a leading dot), -without its sexagesimal, .inf and .nan arms. Both were rewritten as .NET -regular expressions, with a non-capturing group dropped and no other -change to what they match within those arms. + src/Sharpy.Stdlib/Yaml/YamlScalarStyle.cs + +Upstream source: PyYAML 6.0.3, lib/yaml/resolver.py and +lib/yaml/emitter.py (https://github.com/yaml/pyyaml) + +Derived portions: + +- YamlScalarResolver.cs: Yaml11Int is the expression of the implicit + resolver for tag:yaml.org,2002:int, with its binary, octal, decimal and + hexadecimal arms (hexadecimal moved before octal) and without its + sexagesimal arm. Yaml11Float is the first two arms of the resolver for + tag:yaml.org,2002:float (digits with a required dot, and a leading + dot), without its sexagesimal, .inf and .nan arms. Both were rewritten + as .NET regular expressions, with a non-capturing group dropped and no + other change to what they match within those arms. + +- YamlScalarStyle.cs: YamlScalarStyleAuthority.Choose is a C# port of + Emitter.analyze_scalar and Emitter.choose_scalar_style, reduced to the + plain, single-quoted and double-quoted styles: the same flag variables + (block and flow indicators, line breaks, special characters, leading + and trailing space, space followed by a break), the document-indicator + check, the leading and inner indicator character sets, and the order + of the style decision. It drops the block styles, the simple-key + context, canonical output, the line-break characters other than \n and + the allow_unicode handling (only C0 controls and DEL are special), and + takes the caller's resolver verdict in place of the event's implicit + flag. The PyYAML license text follows, verbatim from the LICENSE file at PyYAML's 6.0.3 tag @@ -449,49 +464,71 @@ carries the .spy file's notice. API documentation summaries adapted from CPython docstrings ----------------------------------------------------------- -Some one-line API summaries in the files below (a .spy docstring, or a C# -) are sentences taken from the docstrings of CPython's standard -library, Lib/ in CPython 3.15 (compared against 3.15.2). Only those -summaries are derived from CPython: unless a file is also listed above, -its code is Sharpy's own and it carries no PSF header. The summaries are +Some API summaries in the files below (a .spy docstring, or a C# +) contain sentences taken word for word from CPython 3.15's +docstrings (compared against 3.15.2): those of the Python modules in its +Lib/, and the __doc__ strings of its built-in and C-implemented modules +(builtins, math, itertools, posix, _collections and the like). Only those +sentences are derived from CPython: unless a file is also listed above, +its code is Sharpy's own and it carries no PSF header. The sentences are used under the PSF License Version 2, whose text follows this section. A .spy file stands for itself and the C# generated from it. Sharpy files holding these summaries: + src/Sharpy.Core/Any.cs + src/Sharpy.Core/Builtins/Exceptions.cs + src/Sharpy.Core/IList.cs + src/Sharpy.Core/Id.cs src/Sharpy.Core/Partial.Dict/Dict.Methods.cs + src/Sharpy.Core/Partial.Iterator/Iterator.cs + src/Sharpy.Core/Partial.List/List.cs + src/Sharpy.Core/Partial.Set/Set.Methods.cs + src/Sharpy.Core/Reversed.cs + src/Sharpy.Core/StringExtensions.Split.cs + src/Sharpy.Core/StringExtensions.cs + src/Sharpy.Stdlib/Collections/ChainMap.cs + src/Sharpy.Stdlib/Collections/Collections.cs src/Sharpy.Stdlib/Datetime/Datetime.cs src/Sharpy.Stdlib/Heapq/Heapq.Merge.cs + src/Sharpy.Stdlib/Itertools/__Init__.cs src/Sharpy.Stdlib/Logging/LoggingModule.cs src/Sharpy.Stdlib/Pathlib/Path.cs src/Sharpy.Stdlib/Pathlib/__Init__.cs + src/Sharpy.Stdlib/Secrets/Secrets.cs src/Sharpy.Stdlib/spy/calendar_module.spy src/Sharpy.Stdlib/spy/fnmatch_module.spy + src/Sharpy.Stdlib/spy/glob_module.spy src/Sharpy.Stdlib/spy/heapq.spy + src/Sharpy.Stdlib/spy/itertools.spy src/Sharpy.Stdlib/spy/logging_module.spy + src/Sharpy.Stdlib/spy/math_module.spy + src/Sharpy.Stdlib/spy/os_module.spy src/Sharpy.Stdlib/spy/os_path_module.spy src/Sharpy.Stdlib/spy/pathlib_module.spy src/Sharpy.Stdlib/spy/pprint_module.spy + src/Sharpy.Stdlib/spy/shlex_module.spy src/Sharpy.Stdlib/spy/shutil_module.spy src/Sharpy.Stdlib/spy/statistics.spy src/Sharpy.Stdlib/spy/subprocess_module.spy src/Sharpy.Stdlib/spy/textwrap.spy -Upstream source: CPython 3.15, the docstrings of Lib/calendar.py, -collections/__init__.py, fnmatch.py, genericpath.py, heapq.py, -logging/__init__.py, ntpath.py, pathlib/__init__.py, pathlib/types.py, -pprint.py, _pydatetime.py, shutil.py, statistics.py, subprocess.py and -textwrap.py. +Upstream source: CPython 3.15 (https://github.com/python/cpython): the +docstrings of Lib/, and of the built-in and C-implemented modules. Summary of changes: each sentence documents the Sharpy API of the same name. It may differ from its CPython docstring in letter case, line -wrapping and a final full stop; the rest of each Sharpy docstring is -Sharpy's own. The list above is the set of files in which -build_tools/tests/test_third_party_notices.py finds a summary whose first -paragraph (for a C# summary, its whole text or its first sentence) -equals, ignoring letter case, whitespace and a final full stop, the first -paragraph of a docstring in CPython 3.15's Lib/ that is longer than 30 -characters (Lib's test packages, idlelib and site-packages are not read). +wrapping, reStructuredText markup (* and `) and a final full stop. + +Verbatim sentences are what is credited here. The list above is the set +of files in which build_tools/tests/test_third_party_notices.py finds a +paragraph or sentence of a summary that equals, ignoring letter case, +whitespace, * and ` markup and a final full stop, a paragraph or sentence +of at least 30 characters of one of those docstrings (Lib's test +packages, idlelib, site-packages and CPython's test modules are not +read). Paraphrases of CPython docstrings, and text taken from CPython's +documentation (Doc/*.rst), are not matched, were not audited, and are not +listed. The CPython license text follows, verbatim from the LICENSE.txt shipped with CPython 3.15.2 (lib/python3.15/LICENSE.txt). It is the complete file. diff --git a/build_tools/tests/test_third_party_notices.py b/build_tools/tests/test_third_party_notices.py index 58ae595848..a01f5fbdab 100644 --- a/build_tools/tests/test_third_party_notices.py +++ b/build_tools/tests/test_third_party_notices.py @@ -35,10 +35,21 @@ from __future__ import annotations import hashlib +import inspect import re import sys from pathlib import Path -from typing import Dict, FrozenSet, Iterable, List, Set, Tuple +from typing import ( + Callable, + Dict, + FrozenSet, + Iterable, + List, + Mapping, + Optional, + Set, + Tuple, +) import pytest @@ -104,12 +115,23 @@ def _has_header(text: str) -> bool: return all(line in text for line in HEADER_LINES) -def listed_files( - notices: str, label: str = "Sharpy files derived from it:" -) -> Set[str]: - """The paths under the first `label` line (one per 4-space-indented line).""" +CPYTHON_LABEL = "Sharpy files derived from it:" + + +def cpython_heading(lines: List[str]) -> int: + """The index of the CPython section's heading ("CPython" over "=======").""" + for i in range(len(lines) - 1): + if lines[i] == "CPython" and lines[i + 1] == "=" * len("CPython"): + return i + raise ValueError("THIRD-PARTY-NOTICES.txt has no 'CPython' section heading") + + +def listed_files(notices: str, label: str = CPYTHON_LABEL) -> Set[str]: + """The paths under the first `label` line of the CPython section (one per 4-space-indented + line). Read from the CPython heading, so a section before it that uses the same label is never + taken for the CPython list.""" lines = notices.splitlines() - start = lines.index(label) + start = lines.index(label, cpython_heading(lines)) listed: Set[str] = set() for line in lines[start + 1 :]: if not line.strip(): @@ -295,6 +317,114 @@ def test_every_listed_file_has_an_entry(): assert not problems, "\n".join(problems) +def test_the_cpython_list_is_read_from_the_cpython_section(): + # The Unicode and PyYAML sections come before CPython's (its licence must stay the file's + # tail). If one of them used the CPython label, a search from the top would read its list as + # the CPython list; the search starts at the CPython heading instead. + notices = ( + "PyYAML\n======\n\n" + f"{CPYTHON_LABEL}\n\n src/Sharpy.Stdlib/Yaml/Yaml.cs\n\n\n" + "CPython\n=======\n\n" + f"{CPYTHON_LABEL}\n\n src/Sharpy.Core/PyFormat.cs\n src/Sharpy.Core/FloorDiv.cs\n\n" + ) + assert listed_files(notices) == { + "src/Sharpy.Core/PyFormat.cs", + "src/Sharpy.Core/FloorDiv.cs", + } + + +def test_only_the_cpython_section_uses_the_cpython_label(): + lines = NOTICES.read_text(encoding="utf-8").splitlines() + uses = [i for i, line in enumerate(lines) if line == CPYTHON_LABEL] + assert len(uses) == 1 and uses[0] > cpython_heading(lines), ( + f"{CPYTHON_LABEL!r} is the CPython section's label; another section names its files " + "with a label of its own" + ) + + +# ---- Sources other than CPython (Unicode, PyYAML): the notices and the file headers agree ---- +# +# A file derived from a non-CPython source carries a header comment naming it and ending "see +# THIRD-PARTY-NOTICES.txt" (no PSF lines), and is listed under OTHER_LABEL in that source's section. +# The two sets must be equal. What this cannot see is a derived file with neither: review reads it. + +OTHER_LABEL = "Sharpy files derived from this source:" +NOTICES_POINTER = "see THIRD-PARTY-NOTICES.txt" + + +def other_listed_files(notices: str) -> Set[str]: + """The source paths under every OTHER_LABEL line (continuation lines name no path).""" + lines = notices.splitlines() + listed: Set[str] = set() + for i, line in enumerate(lines): + if line != OTHER_LABEL: + continue + block: List[str] = [] + for entry in lines[i + 1 :]: + if not entry.strip(): + if block: + break + continue + if not entry.startswith(" "): + break + block.append(entry) + listed.update(_ENTRY_PATH.findall("\n".join(block))) + return listed + + +def other_headed_files(root: Path) -> Set[str]: + return { + path.relative_to(root).as_posix() + for path in sources(root) + for text in [path.read_text(encoding="utf-8")] + if NOTICES_POINTER in text and not _has_header(text) + } + + +def other_problems(listed: Set[str], headed: Set[str]) -> List[str]: + problems = [ + f"{rel}: points at THIRD-PARTY-NOTICES.txt but is not under {OTHER_LABEL!r}" + for rel in sorted(headed - listed) + ] + problems += [ + f"{rel}: under {OTHER_LABEL!r} but carries no header pointing at the notices" + for rel in sorted(listed - headed) + ] + return problems + + +def test_non_cpython_sources_and_headers_agree(): + notices = NOTICES.read_text(encoding="utf-8") + listed = other_listed_files(notices) + headed = other_headed_files(REPO) + # Positive control: both sections and the files they name are seen. + assert { + "src/Sharpy.Core/StringExtensions.Format.cs", + "src/Sharpy.Stdlib/Yaml/YamlScalarResolver.cs", + } <= listed, sorted(listed) + problems = other_problems(listed, headed) + assert not problems, "\n".join(problems) + lines = notices.splitlines() + uses = [i for i, line in enumerate(lines) if line == OTHER_LABEL] + assert all(i < cpython_heading(lines) for i in uses), ( + f"{OTHER_LABEL!r} labels the sections before CPython's only" + ) + + +def test_non_cpython_check_refuses_either_side_alone(tmp_path: Path): + notices = ( + f"PyYAML\n======\n\n{OTHER_LABEL}\n\n src/Sharpy.Stdlib/Yaml/A.cs (only X)\n" + " src/Sharpy.Stdlib/Yaml/B.cs\n\n" + ) + listed = other_listed_files(notices) + assert listed == {"src/Sharpy.Stdlib/Yaml/A.cs", "src/Sharpy.Stdlib/Yaml/B.cs"} + assert other_problems(listed, listed) == [] + unheaded = other_problems(listed, {"src/Sharpy.Stdlib/Yaml/A.cs"}) + assert len(unheaded) == 1 and "B.cs: under" in unheaded[0], unheaded + unlisted = other_problems({"src/Sharpy.Stdlib/Yaml/A.cs"}, listed) + assert len(unlisted) == 1 and "B.cs: points at" in unlisted[0], unlisted + + # ---- The #2602 census: every Stdlib module with a CPython namesake, read against its source ---- STDLIB = "src/Sharpy.Stdlib" @@ -634,26 +764,63 @@ def test_census_names_a_malformed_row(tmp_path: Path, row): # ---- API summaries adapted from CPython docstrings (#2602 follow-up, owner 2026-11-20) ---- # -# Some one-line API summaries (a .spy docstring, a C# ) are CPython Lib docstrings copied -# word for word. That is documentation, not code: the files keep no PSF header (a "behaviour" census -# row stays header-free), and THIRD-PARTY-NOTICES.txt credits them in one section whose file list -# must equal the set this matcher finds. The rule is the #2777 review's: a summary matches when its -# first paragraph (a C# summary: the whole text or its first sentence), whitespace collapsed, case -# and a final full stop ignored, equals the first paragraph of a docstring (module, class or -# function) in CPython's Lib that is longer than DOCSTRING_MIN characters. Lib's test packages, -# idlelib and site-packages are not read. C# generated from a .spy file is skipped: the .spy file is -# listed for it, as the notices file says. +# Some API summaries (a .spy docstring, a C# ) repeat CPython docstring sentences word for +# word. That is documentation, not code: the files keep no PSF header (a "behaviour" census row stays +# header-free), and THIRD-PARTY-NOTICES.txt credits them in one section whose file list must equal +# the set this matcher finds. +# +# The rule (#2777 review, widened by the #2780 review): `doc_keys` turns a text into keys, one per +# paragraph and one per sentence of each paragraph, with `*` and backticks (reST markup) removed, +# whitespace collapsed, case and a final full stop ignored. The index holds every key of at least +# DOCSTRING_MIN characters from (a) the module, class and function docstrings of CPython's Lib (its +# test packages, idlelib and site-packages are not read) and (b) the __doc__ of every built-in or +# C-implemented module (sys.builtin_module_names and lib-dynload, test modules aside), of its +# functions and classes, and of their methods and descriptors. A Sharpy file is a match when a key +# of one of its .spy docstrings or C# summaries is in the index. C# generated from a .spy file is +# skipped: the .spy file is listed for it, as the notices file says. Paraphrases, and text from +# CPython's Doc/*.rst, are not matched (the notices file says so). +# +# The oracle is the CPython minor in .python-version. Without that interpreter the guard skips +# locally and fails on CI (`CI` set), so moving the oracle can never turn it into a silent skip. DOCSTRING_LABEL = "Sharpy files holding these summaries:" +DOCSTRING_HEADING = "API documentation summaries adapted from CPython docstrings" DOCSTRING_MIN = 30 -DOCSTRING_ORACLE = (3, 15) +PYTHON_VERSION_FILE = REPO / ".python-version" + + +def doc_keys(text): + """The match keys of a docstring or summary: each paragraph, and each sentence in it.""" + import re + + keys = [] + for para in text.strip().split("\n\n"): + flat = " ".join(re.sub(r"[*`]", "", para).split()) + for part in [flat] + re.split(r"(?<=[.!?])\s+(?=[A-Z])", flat): + keys.append(part.rstrip(".").lower()) + return keys + -# Run under the oracle's python (`-I`): prints {"version": ..., "index": {key: Lib-relative path}}. -# argv[1], when given, is the Lib directory to read instead of the interpreter's own. -_INDEX_SCRIPT = r""" -import ast, json, os, sys -lib = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.__file__) +# Run under the oracle's python (`-I`): prints {"version": ..., "index": {key: where}}, `where` being +# "Lib/" or ".". argv[1], when not empty, is the Lib directory to read instead of +# the interpreter's own; argv[2] == "--no-runtime" skips the built-in and C-implemented modules. +_INDEX_SCRIPT = ( + inspect.getsource(doc_keys) + + r""" +import ast, importlib, inspect, json, os, sys + +MIN = %d +lib = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] else os.path.dirname(os.__file__) +runtime = not (len(sys.argv) > 2 and sys.argv[2] == "--no-runtime") index = {} + + +def add(doc, where): + for key in doc_keys(doc): + if len(key) >= MIN: + index.setdefault(key, where) + + for dirpath, dirnames, filenames in os.walk(lib): dirnames.sort() for name in sorted(filenames): @@ -672,42 +839,76 @@ def test_census_names_a_malformed_row(tmp_path: Path, row): if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): doc = ast.get_docstring(node) if doc: - first = " ".join(doc.strip().split("\n\n")[0].split()) - if len(first) > MIN: - index.setdefault(first.rstrip(".").lower(), rel) + add(doc, "Lib/" + rel) + + +def members(module, label): + for name, obj in sorted(vars(module).items()): + if not (inspect.isroutine(obj) or inspect.isclass(obj)): + continue + if isinstance(obj.__doc__, str): + add(obj.__doc__, label + "." + name) + if not inspect.isclass(obj): + continue + for attr, member in sorted(vars(obj).items()): + if not ( + inspect.isroutine(member) + or inspect.isdatadescriptor(member) + or isinstance(member, (classmethod, staticmethod)) + ): + continue + doc = getattr(member, "__doc__", None) + if isinstance(doc, str): + add(doc, label + "." + name + "." + attr) + + +if runtime: + names = set(sys.builtin_module_names) + dynload = os.path.join(lib, "lib-dynload") + if os.path.isdir(dynload): + names.update( + f.split(".")[0] for f in os.listdir(dynload) if f.endswith((".so", ".pyd")) + ) + for name in sorted(names): + if name.startswith(("_test", "_xx", "xx")): + continue + try: + module = importlib.import_module(name) + except Exception: + continue + if isinstance(module.__doc__, str): + add(module.__doc__, name) + members(module, name) + print(json.dumps({"version": list(sys.version_info[:3]), "index": index})) -""".replace("MIN", str(DOCSTRING_MIN)) +""" + % DOCSTRING_MIN +) _SPY_DOCSTRING = re.compile(r'"""(.*?)"""', re.S) _CS_SUMMARY = re.compile(r"(.*?)", re.S) _GENERATED = "// Generated from" -def _key(text: str) -> str: - return " ".join(text.strip().split("\n\n")[0].split()).rstrip(".").lower() - - def summary_keys(path: Path, text: str) -> List[str]: - """The match keys of a file's summaries (a C# summary gives its whole text and first sentence).""" + """The match keys of a file's .spy docstrings or C# summaries.""" if path.suffix == ".spy": - return [_key(m.group(1)) for m in _SPY_DOCSTRING.finditer(text)] + return [k for m in _SPY_DOCSTRING.finditer(text) for k in doc_keys(m.group(1))] if text.startswith(_GENERATED): return [] keys = [] for m in _CS_SUMMARY.finditer(text): - summary = re.sub(r"<[^>]+>", "", re.sub(r"\s*///\s*", " ", m.group(1))) - whole = " ".join(summary.split()).rstrip(".").lower() - keys += [whole, whole.split(". ")[0]] + keys += doc_keys(re.sub(r"<[^>]+>", "", re.sub(r"\s*///\s*", " ", m.group(1)))) return keys def docstring_matches(root: Path, index: Dict[str, str]) -> Dict[str, List[str]]: - """Root-relative path -> 'summary <- Lib path' for each summary found in the CPython index.""" + """Root-relative path -> "'key' <- where" for each of its keys found in the CPython index.""" found: Dict[str, List[str]] = {} for path in sources(root): hits = sorted( { - f"{key!r} <- Lib/{index[key]}" + f"{key!r} <- {index[key]}" for key in summary_keys(path, path.read_text(encoding="utf-8")) if key in index } @@ -731,41 +932,82 @@ def docstring_problems(listed: Set[str], found: Dict[str, List[str]]) -> List[st return problems -def _run_index(python: str, lib: str = "") -> Dict[str, object]: +def oracle_minor(version_file: Path) -> Tuple[int, int]: + """The CPython minor .python-version names (its first line that is not a comment).""" + for line in version_file.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + m = re.match(r"(\d+)\.(\d+)", line) + if m: + return int(m.group(1)), int(m.group(2)) + break + raise ValueError(f"{version_file}: no CPython minor") + + +def resolve_oracle( + oracle: Tuple[int, int], + version: Tuple[int, ...], + executable: str, + which: Callable[[str], Optional[str]], + environ: Mapping[str, str], +) -> Tuple[str, str]: + """("run", python), or ("skip" | "fail", reason): fail on CI, where the oracle must exist.""" + if tuple(version[:2]) == oracle: + return "run", executable + name = "python%d.%d" % oracle + found = which(name) + if found: + return "run", found + reason = ( + f"the docstring oracle is CPython {oracle[0]}.{oracle[1]} (.python-version); this is " + f"Python {version[0]}.{version[1]} and {name} is not on PATH" + ) + return ("fail" if environ.get("CI") else "skip"), reason + + +def _run_index(python: str, lib: str = "", runtime: bool = True) -> Dict[str, object]: import json import subprocess - argv = [python, "-I", "-c", _INDEX_SCRIPT] + ([lib] if lib else []) + argv = [python, "-I", "-c", _INDEX_SCRIPT, lib] + ( + [] if runtime else ["--no-runtime"] + ) out = subprocess.run(argv, check=True, capture_output=True, text=True).stdout return json.loads(out) @pytest.fixture(scope="module") def cpython_docstrings() -> Dict[str, str]: + import os import shutil - if sys.version_info[:2] == DOCSTRING_ORACLE: - python = sys.executable - else: - python = shutil.which("python%d.%d" % DOCSTRING_ORACLE) or "" - if not python: - pytest.skip( - "the docstring oracle is CPython %d.%d's Lib (.python-version); " - "python%d.%d is not on PATH" % (DOCSTRING_ORACLE * 2) - ) - result = _run_index(python) - assert tuple(result["version"][:2]) == DOCSTRING_ORACLE, result["version"] + oracle = oracle_minor(PYTHON_VERSION_FILE) + action, value = resolve_oracle( + oracle, sys.version_info, sys.executable, shutil.which, os.environ + ) + if action == "fail": + pytest.fail(value) + if action == "skip": + pytest.skip(value) + result = _run_index(value) + assert tuple(result["version"][:2]) == oracle, result["version"] return result["index"] def test_docstring_matcher_sees_the_known_summaries(cpython_docstrings): - # Positive control: an empty result elsewhere means "none", not "looked nowhere". - assert cpython_docstrings.get( - "push item onto heap, maintaining the heap invariant" - ) == ("heapq.py") + # Positive control: an empty result elsewhere means "none", not "looked nowhere". One Lib + # docstring and one C-implemented one (math.cosh) are in the index, and files holding each are + # found. + assert ( + cpython_docstrings.get("push item onto heap, maintaining the heap invariant") + == "Lib/heapq.py" + ) + assert cpython_docstrings.get("return the hyperbolic cosine of x") == "math.cosh" found = docstring_matches(REPO, cpython_docstrings) assert { "src/Sharpy.Stdlib/spy/heapq.spy", + "src/Sharpy.Stdlib/spy/math_module.spy", "src/Sharpy.Stdlib/Pathlib/Path.cs", } <= set(found), sorted(found) @@ -780,12 +1022,25 @@ def test_docstring_notice_lists_exactly_the_files_holding_cpython_docstrings( assert not problems, "\n".join(problems) -def test_docstring_index_reads_first_paragraphs_over_the_minimum(tmp_path: Path): - # The index rule, run by this interpreter over a stand-in Lib (no oracle needed). - long = "Return the frobnicated value of the given widget." +def test_docstring_notice_names_the_oracle_minor(): + notices = NOTICES.read_text(encoding="utf-8") + section = notices[notices.index(DOCSTRING_HEADING) :] + section = section[: section.index("The CPython license text follows")] + major, minor = oracle_minor(PYTHON_VERSION_FILE) + assert f"CPython {major}.{minor}" in section, ( + "the docstring section names the oracle CPython minor of .python-version" + ) + + +def test_docstring_index_rule_over_a_stand_in_lib(tmp_path: Path): + # The index rule, run by this interpreter over a stand-in Lib (no oracle needed): every + # paragraph and sentence over the minimum, reST markup removed, test packages not read. (tmp_path / "frob.py").write_text( - f'"""Frobnication helpers for widgets and gadgets.\n\nMore text."""\n' - f'def frob(x):\n """{long}\n\n Details."""\n' + '"""Frobnication helpers for widgets and gadgets.\n\nMore text."""\n' + "def frob(x):\n" + ' """Return the frobnicated value of the given *widget*.\n\n' + " Super-frob; frobnicate a widget and all its ``parts``. Short one.\n" + ' """\n' 'def short(x):\n """Return x unchanged here."""\n', encoding="utf-8", ) @@ -793,14 +1048,27 @@ def test_docstring_index_reads_first_paragraphs_over_the_minimum(tmp_path: Path) (tmp_path / "test" / "test_frob.py").write_text( '"""A test module docstring that is long enough."""\n', encoding="utf-8" ) - index = _run_index(sys.executable, str(tmp_path))["index"] + index = _run_index(sys.executable, str(tmp_path), runtime=False)["index"] assert index == { - "frobnication helpers for widgets and gadgets": "frob.py", - long.rstrip(".").lower(): "frob.py", + "frobnication helpers for widgets and gadgets": "Lib/frob.py", + "return the frobnicated value of the given widget": "Lib/frob.py", + "super-frob; frobnicate a widget and all its parts. short one": "Lib/frob.py", + "super-frob; frobnicate a widget and all its parts": "Lib/frob.py", } -_FAKE_INDEX = {"return the frobnicated value of the given widget": "frob.py"} +def test_docstring_index_reads_c_implemented_modules(): + # The runtime half, under this interpreter: built-in functions and methods are indexed. + index = _run_index(sys.executable, "/nonexistent-lib")["index"] + assert index.get("return the identity of an object") == "builtins.id" + assert index.get("return a shallow copy of the list") == "builtins.list.copy" + + +_FAKE_INDEX = { + "return the frobnicated value of the given widget": "Lib/frob.py", + "super-frob; frobnicate a widget and all its parts": "Lib/frob.py", + "serialize obj to a json formatted str": "Lib/json/__init__.py", +} def _source(tmp_path: Path, rel: str, text: str) -> None: @@ -817,14 +1085,22 @@ def _source(tmp_path: Path, rel: str, text: str) -> None: 'def frob(x: int) -> int:\n """Return the frobnicated value of the\n' ' given widget.\n\n Sharpy details."""\n', ), + ( # a later paragraph's sentence + "src/Sharpy.Stdlib/spy/frob.spy", + 'def frob(x: int) -> int:\n """Frob it.\n\n' + ' Super-frob; frobnicate a widget and all its parts. Sharpy adds more."""\n', + ), + ( # reST markup on the Sharpy side + "src/Sharpy.Stdlib/spy/frob.spy", + 'def dumps(obj: object) -> str:\n """Serialize ``obj`` to a JSON formatted ``str``."""\n', + ), ( "src/Sharpy.Stdlib/Frob/Frob.cs", "/// \n/// Return the frobnicated value of the given widget.\n/// \n", ), - ( + ( # a later sentence of a C# summary "src/Sharpy.Core/Frob.cs", - "/// Return the frobnicated value of the given widget. Sharpy adds more." - "\n", + "/// Frobs. Return the frobnicated value of the given widget. More.\n", ), ], ) @@ -850,3 +1126,26 @@ def test_docstring_check_refuses_a_stale_line_and_skips_generated_csharp( assert found == {} problems = docstring_problems({"src/Sharpy.Stdlib/Frob/Frob.cs"}, found) assert len(problems) == 1 and "delete the line" in problems[0], problems + + +def test_oracle_minor_reads_the_version_file(tmp_path: Path): + path = tmp_path / ".python-version" + path.write_text("# a comment\n\n3.16\n", encoding="utf-8") + assert oracle_minor(path) == (3, 16) + assert oracle_minor(PYTHON_VERSION_FILE)[0] == 3 + + +@pytest.mark.parametrize( + "version, which, environ, expected", + [ + ((3, 16, 0), None, {}, ("run", "/py/self")), # this interpreter is the oracle + ((3, 15, 2), "/bin/python3.16", {}, ("run", "/bin/python3.16")), + ((3, 15, 2), None, {}, ("skip", "python3.16 is not on PATH")), + ((3, 15, 2), None, {"CI": "true"}, ("fail", "python3.16 is not on PATH")), + ], +) +def test_the_oracle_skips_locally_and_fails_on_ci(version, which, environ, expected): + action, value = resolve_oracle( + (3, 16), version, "/py/self", lambda name: which, environ + ) + assert action == expected[0] and expected[1] in value, (action, value) diff --git a/src/Sharpy.Cli/Sharpy.Cli.csproj b/src/Sharpy.Cli/Sharpy.Cli.csproj index 4aa54d2c05..7e00b893f5 100644 --- a/src/Sharpy.Cli/Sharpy.Cli.csproj +++ b/src/Sharpy.Cli/Sharpy.Cli.csproj @@ -12,7 +12,7 @@ sharpyc Sharpy compiler — a statically-typed Pythonic language for .NET. Compile .spy files to C# and run them on the CLR. README.md - + (Apache-2.0 OR MIT) AND Python-2.0 AND Unicode-3.0 AND MIT diff --git a/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj b/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj index 250c006727..dd431c5a2c 100644 --- a/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj +++ b/src/Sharpy.Stdlib/Sharpy.Stdlib.csproj @@ -13,7 +13,7 @@ true Standard library for the Sharpy programming language. Provides json, os, re, math, and 60+ modules with Pythonic APIs on .NET. README.md - + (Apache-2.0 OR MIT) AND Python-2.0 AND MIT diff --git a/src/Sharpy.Stdlib/Yaml/YamlScalarStyle.cs b/src/Sharpy.Stdlib/Yaml/YamlScalarStyle.cs index da19680410..cb7e66c252 100644 --- a/src/Sharpy.Stdlib/Yaml/YamlScalarStyle.cs +++ b/src/Sharpy.Stdlib/Yaml/YamlScalarStyle.cs @@ -1,3 +1,6 @@ +// YamlScalarStyleAuthority.Choose is ported from PyYAML 6.0.3's Emitter.analyze_scalar and +// Emitter.choose_scalar_style (lib/yaml/emitter.py), Copyright (c) 2017-2021 Ingy döt Net and +// Copyright (c) 2006-2016 Kirill Simonov, used under the MIT License; see THIRD-PARTY-NOTICES.txt. namespace Sharpy { /// From 9d31a5ddd3772f10c86cecef5bc2052e5e902321 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:06:42 +0000 Subject: [PATCH 6/6] test: tighten the notices guards after the second #2780 review The second review of 813d1412d..978124ccb said "merge" with four cheap follow-ups: 1. A file counts as pointing at the notices when it names THIRD-PARTY-NOTICES anywhere, in any case ("See ... ." included), and carries no PSF header; the old exact "see THIRD-PARTY-NOTICES.txt" missed natural wording. Today that set is exactly the three listed files: StringExtensions.Format.cs, YamlScalarResolver.cs and YamlScalarStyle.cs. A unit test covers three wordings and the PSF exclusion. 2. The index skips every module whose name contains "test" (e.g. _ctypes_test, which CI's build ships and the _test prefix missed) and the xx example modules, through indexed_module(), embedded in the index script and unit-tested over a stand-in module list. 3. The docstring section must name no CPython minor but the oracle's (every 3.N or 3.N.M in it), not merely contain it. 4. CI counts as set only for "true" or "1", in any case; CI=false, 0 and empty skip. The fake-environment test covers all six. Mutations (each restored with cp, checked with cmp: all "cmp ok"): | # | mutation | result | |---|--------------------------------------------------|---------------| | r1| "// Derived from Foo 1.0 (MIT License). See | red 1/82 | | | THIRD-PARTY-NOTICES.txt." atop unlisted Len.cs | | | r2| indexed_module back to the _test/_xx/xx prefixes | red 1/82 | | | (_ctypes_test read) | | | r3| notices "CPython 3.15's" -> "CPython 3.16's" | red 1/82 | | r4| on_ci = bool(environ.get("CI")) | red 2/81 | | | (CI=false and CI=0 fail instead of skipping) | | (failed/passed in test_third_party_notices.py; green 83 passed.) Gate: test_third_party_notices.py + test_package_licenses.py 99 passed; pytest build_tools/tests (python3.15) 2284 passed / 0 failed / 0 skipped; scorecard_metrics --check OK. Only this test file changed. Refs #2602 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/tests/test_third_party_notices.py | 66 +++++++++++++++++-- 1 file changed, 59 insertions(+), 7 deletions(-) diff --git a/build_tools/tests/test_third_party_notices.py b/build_tools/tests/test_third_party_notices.py index a01f5fbdab..d848cb3adb 100644 --- a/build_tools/tests/test_third_party_notices.py +++ b/build_tools/tests/test_third_party_notices.py @@ -344,12 +344,14 @@ def test_only_the_cpython_section_uses_the_cpython_label(): # ---- Sources other than CPython (Unicode, PyYAML): the notices and the file headers agree ---- # -# A file derived from a non-CPython source carries a header comment naming it and ending "see -# THIRD-PARTY-NOTICES.txt" (no PSF lines), and is listed under OTHER_LABEL in that source's section. -# The two sets must be equal. What this cannot see is a derived file with neither: review reads it. +# A file derived from a non-CPython source carries a header comment naming it and pointing at +# THIRD-PARTY-NOTICES.txt (no PSF lines), and is listed under OTHER_LABEL in that source's section. +# A file is "headed" when it names THIRD-PARTY-NOTICES anywhere, in any case and wording ("see", +# "See ... .", a bare mention), and carries no PSF header. The two sets must be equal. What this +# cannot see is a derived file with neither: review reads it. OTHER_LABEL = "Sharpy files derived from this source:" -NOTICES_POINTER = "see THIRD-PARTY-NOTICES.txt" +NOTICES_POINTER = re.compile(r"THIRD-PARTY-NOTICES", re.IGNORECASE) def other_listed_files(notices: str) -> Set[str]: @@ -377,7 +379,7 @@ def other_headed_files(root: Path) -> Set[str]: path.relative_to(root).as_posix() for path in sources(root) for text in [path.read_text(encoding="utf-8")] - if NOTICES_POINTER in text and not _has_header(text) + if NOTICES_POINTER.search(text) and not _has_header(text) } @@ -425,6 +427,22 @@ def test_non_cpython_check_refuses_either_side_alone(tmp_path: Path): assert len(unlisted) == 1 and "B.cs: points at" in unlisted[0], unlisted +@pytest.mark.parametrize( + "header", + [ + "// Derived from Foo 1.0 (MIT License). See THIRD-PARTY-NOTICES.txt.", + "// from Foo 1.0, used under the MIT License; see THIRD-PARTY-NOTICES.txt.", + "/* Foo's tables (see third-party-notices.txt) */", + ], +) +def test_any_pointer_at_the_notices_marks_a_file_headed(tmp_path: Path, header: str): + _source(tmp_path, "src/Sharpy.Stdlib/Foo/Foo.cs", header + "\nnamespace Sharpy { }\n") + _source(tmp_path, "src/Sharpy.Stdlib/Foo/Plain.cs", "namespace Sharpy { }\n") + psf = "".join(f"// {line}\n" for line in HEADER_LINES) # a CPython port, not this guard's + _source(tmp_path, "src/Sharpy.Core/Port.cs", psf + "namespace Sharpy { }\n") + assert other_headed_files(tmp_path) == {"src/Sharpy.Stdlib/Foo/Foo.cs"} + + # ---- The #2602 census: every Stdlib module with a CPython namesake, read against its source ---- STDLIB = "src/Sharpy.Stdlib" @@ -801,11 +819,18 @@ def doc_keys(text): return keys +def indexed_module(name): + """Whether the index reads a built-in or C-implemented module: never a test module (any name + containing "test", e.g. _testcapi or _ctypes_test) or one of CPython's xx example modules.""" + return "test" not in name.lower() and not name.lstrip("_").startswith("xx") + + # Run under the oracle's python (`-I`): prints {"version": ..., "index": {key: where}}, `where` being # "Lib/" or ".". argv[1], when not empty, is the Lib directory to read instead of # the interpreter's own; argv[2] == "--no-runtime" skips the built-in and C-implemented modules. _INDEX_SCRIPT = ( inspect.getsource(doc_keys) + + inspect.getsource(indexed_module) + r""" import ast, importlib, inspect, json, os, sys @@ -870,7 +895,7 @@ def members(module, label): f.split(".")[0] for f in os.listdir(dynload) if f.endswith((".so", ".pyd")) ) for name in sorted(names): - if name.startswith(("_test", "_xx", "xx")): + if not indexed_module(name): continue try: module = importlib.import_module(name) @@ -963,7 +988,8 @@ def resolve_oracle( f"the docstring oracle is CPython {oracle[0]}.{oracle[1]} (.python-version); this is " f"Python {version[0]}.{version[1]} and {name} is not on PATH" ) - return ("fail" if environ.get("CI") else "skip"), reason + on_ci = environ.get("CI", "").lower() in ("true", "1") + return ("fail" if on_ci else "skip"), reason def _run_index(python: str, lib: str = "", runtime: bool = True) -> Dict[str, object]: @@ -1030,6 +1056,14 @@ def test_docstring_notice_names_the_oracle_minor(): assert f"CPython {major}.{minor}" in section, ( "the docstring section names the oracle CPython minor of .python-version" ) + named = { + (int(a), int(b)) + for a, b in re.findall(r"(?