From caea032f11f408404cad6fcc080b7021c1b1d7e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:16:11 +0000 Subject: [PATCH 1/3] build: complete the CPython notices (#2602 audit) Charter row R-NJ (a): read every Sharpy.Stdlib module with a CPython 3.15 namesake (55 modules) against its CPython source, plus the Core files that follow CPython's implementation, and notice every port. Ports (PSF header + THIRD-PARTY-NOTICES.txt entry): - Stdlib: Colorsys.cs; Difflib SequenceMatcher.cs, Differ.cs, DifflibFunctions.cs; Fraction.cs (limit_denominator); Threading Barrier.cs; Ipaddress AddressFormat.cs, IPv4Address.cs, IPv6Address.cs (borderline: __format__ and the _private_networks tables); Urllib UrllibModule.cs (borderline: uses_netloc/uses_params); spy-sourced fnmatch_module.spy, itertools.spy (borderline: the docs' equivalents), os_module.spy and shutil_module.spy (borderline), with their generated C#. - Core: PyFormatSpec.cs (parse_internal_render_format_spec), FloorDiv.cs and FloorMod.cs (_float_div_mod / float_rem), NumericText.cs (borderline: _PyUnicode_TransformDecimalAndSpaceToASCII), UnicodeCodec.cs (borderline: encodings.aliases rows); PyFormat.cs's entry now also names RenderComplex (format_complex_internal's set-up). The other 44 namesake modules are behaviour-only; Str.cs and ThreadRegistry.cs stay behaviour-only. regenerate_spy_stdlib.sh carries a .spy file's leading # comment block into the generated C# as // lines, so the shipped C# keeps the notice; the generated files change only by those comment lines. The notices intro drops the "not yet exhaustive" sentence and its list of open files. test_third_party_notices.py gains STDLIB_CENSUS (module -> port | behaviour for every namesake module on disk) and a check that every listed file has a numbered entry. Mutation record (each red, then restored from a cp copy, then 45 passed): - fake src/Sharpy.Stdlib/Pickle/Pickle.cs: 1 failed (test_stdlib_census_is_complete_and_honoured: no STDLIB_CENSUS row) - Colorsys verdict port -> behaviour, header kept: 1 failed (census: verdict 'behaviour' but the file carries the header) - delete the "Licensed under" line of Colorsys.cs: 3 failed (claim scan, notices_and_headers_agree, census) - delete the numbered Colorsys entry: 1 failed (test_every_listed_file_has_an_entry) - delete the Colorsys line of the file list: 4 failed - regenerate with the notice carry disabled: 2 failed (notices_and_headers_agree, census); restored script, regenerated, green Refs #2602 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- THIRD-PARTY-NOTICES.txt | 275 +++++++++++++++++- build_tools/regenerate_spy_stdlib.sh | 7 + build_tools/tests/test_third_party_notices.py | 266 ++++++++++++++++- src/Sharpy.Core/FloorDiv.cs | 8 + src/Sharpy.Core/FloorMod.cs | 7 + src/Sharpy.Core/NumericText.cs | 7 + src/Sharpy.Core/PyFormat.cs | 11 +- src/Sharpy.Core/PyFormatSpec.cs | 10 + src/Sharpy.Core/UnicodeCodec.cs | 7 + src/Sharpy.Stdlib/Colorsys/Colorsys.cs | 7 + src/Sharpy.Stdlib/Difflib/Differ.cs | 9 + src/Sharpy.Stdlib/Difflib/DifflibFunctions.cs | 8 + src/Sharpy.Stdlib/Difflib/SequenceMatcher.cs | 8 + src/Sharpy.Stdlib/Fnmatch/FnmatchModule.cs | 7 + src/Sharpy.Stdlib/Fractions/Fraction.cs | 7 + src/Sharpy.Stdlib/Ipaddress/AddressFormat.cs | 9 + src/Sharpy.Stdlib/Ipaddress/IPv4Address.cs | 8 + src/Sharpy.Stdlib/Ipaddress/IPv6Address.cs | 8 + src/Sharpy.Stdlib/Itertools/Itertools.cs | 7 + src/Sharpy.Stdlib/Os/Os.cs | 7 + src/Sharpy.Stdlib/Shutil/Shutil.cs | 6 + src/Sharpy.Stdlib/Threading/Barrier.cs | 8 + src/Sharpy.Stdlib/Urllib/UrllibModule.cs | 7 + src/Sharpy.Stdlib/spy/fnmatch_module.spy | 8 + src/Sharpy.Stdlib/spy/itertools.spy | 8 + src/Sharpy.Stdlib/spy/os_module.spy | 8 + src/Sharpy.Stdlib/spy/shutil_module.spy | 7 + 27 files changed, 713 insertions(+), 22 deletions(-) diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 30d638ab72..76048d2b8d 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -4,15 +4,12 @@ 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. The components identified so far are listed below, -each with the Sharpy files derived from it, the upstream source, and the full -license text under which it is used. This list is not yet exhaustive. The -audit of CPython-derived code, including files that do not describe -themselves as ports, is tracked in issue #2602 of the Sharpy repository. -Among the files still open in that audit are, for example, -src/Sharpy.Core/PyFormatSpec.cs, src/Sharpy.Stdlib/Threading/Barrier.cs, -src/Sharpy.Core/Str.cs (the format_float_short layout rule) and -src/Sharpy.Stdlib/Threading/ThreadRegistry.cs. +under its own license. Each such component is listed below, 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. CPython @@ -25,11 +22,36 @@ Sharpy files derived from it: src/Sharpy.Stdlib/Datetime/DatetimeIso.cs src/Sharpy.Stdlib/Fractions/Fraction.Format.cs src/Sharpy.Core/PyFormat.cs + src/Sharpy.Core/PyFormatSpec.cs + src/Sharpy.Core/FloorDiv.cs + src/Sharpy.Core/FloorMod.cs + src/Sharpy.Core/NumericText.cs + src/Sharpy.Core/UnicodeCodec.cs + src/Sharpy.Stdlib/Colorsys/Colorsys.cs + src/Sharpy.Stdlib/Difflib/SequenceMatcher.cs + src/Sharpy.Stdlib/Difflib/Differ.cs + src/Sharpy.Stdlib/Difflib/DifflibFunctions.cs + src/Sharpy.Stdlib/Fractions/Fraction.cs + src/Sharpy.Stdlib/Threading/Barrier.cs + src/Sharpy.Stdlib/Ipaddress/AddressFormat.cs + src/Sharpy.Stdlib/Ipaddress/IPv4Address.cs + src/Sharpy.Stdlib/Ipaddress/IPv6Address.cs + src/Sharpy.Stdlib/Urllib/UrllibModule.cs + src/Sharpy.Stdlib/spy/fnmatch_module.spy + src/Sharpy.Stdlib/Fnmatch/FnmatchModule.cs + src/Sharpy.Stdlib/spy/itertools.spy + src/Sharpy.Stdlib/Itertools/Itertools.cs + src/Sharpy.Stdlib/spy/os_module.spy + src/Sharpy.Stdlib/Os/Os.cs + src/Sharpy.Stdlib/spy/shutil_module.spy + src/Sharpy.Stdlib/Shutil/Shutil.cs Upstream: https://github.com/python/cpython Each file's derived portions and the summary of changes required by clause 3 -of the PSF License Version 2 follow. +of the PSF License Version 2 follow. A .spy file and the C# generated from it +by build_tools/regenerate_spy_stdlib.sh share one entry; the generated file +carries the .spy file's notice. 1. src/Sharpy.Stdlib/Datetime/DatetimeIso.cs @@ -65,16 +87,241 @@ of the PSF License Version 2 follow. raises ValueError. The entry point is IFormattable.ToString, and errors are raised as Sharpy's ValueError. -3. src/Sharpy.Core/PyFormat.cs (only the private method - InsertThousandsGrouping) +3. src/Sharpy.Core/PyFormat.cs (only the private methods + InsertThousandsGrouping and RenderComplex) Upstream source: _PyUnicode_InsertThousandsGrouping, in CPython's C - implementation (Objects/). + implementation (Objects/), and format_complex_internal in CPython 3.14, + Python/formatter_unicode.c. + + Ported to C#: the thousands-grouping loop, and the set-up of + format_complex_internal (the 'r' default type when no type is given, + skip_re and add_parens for a +0 real part, 'n' read as 'g', and the + imaginary part's forced sign). Summary of changes: translated from C to C#. Only a uniform group size is handled (no locale grouping string), and the result is built as a .NET string from right to left instead of being written into a preallocated - Unicode buffer. + Unicode buffer. The complex parts are rendered by Sharpy's own float + formatting and padded as one string. + +4. src/Sharpy.Core/PyFormatSpec.cs + + Upstream source: CPython 3.14, Python/formatter_unicode.c + + Ported to C#: parse_internal_render_format_spec (fill and alignment, sign, + 'z', '#', the backward-compatible '0' flag, width, the ',' and '_' + separators and their conflict, precision) and get_integer, and the order + and messages of the refusals in format_string_internal, + format_long_internal, format_complex_internal and the str, int, float and + complex __format__ switches. + + Summary of changes: translated from C to C#. The parser returns a + PyFormatSpec value or a FormatSpecError instead of filling an + InternalFormatSpec and setting a Python exception; the grouping-with-type + check runs in Validate, where the operand's default type is known; the + fractional-part separators are not supported; digits are read as Unicode + decimal digits from a UTF-16 string. + +5. src/Sharpy.Core/FloorDiv.cs (only the double and float overloads of + FloorDiv) + + Upstream source: CPython 3.14, Objects/floatobject.c + + Ported to C#: the quotient half of _float_div_mod, which float_floor_div + uses (div = (vx - mod) / wx, the adjustment when the remainder's sign + differs from the divisor's, the snap to the nearest integral value, and + the signed zero quotient). + + Summary of changes: translated from C to C#. fmod is the C# % operator, + copysign(0.0, vx / wx) is a sign-bit test (netstandard2.1 has no + Math.CopySign), the float overload repeats the algorithm in single + precision, and a zero divisor raises Sharpy's ZeroDivisionError. + +6. src/Sharpy.Core/FloorMod.cs (only the double and float overloads of + FloorMod) + + Upstream source: CPython 3.14, Objects/floatobject.c + + Ported to C#: float_rem (the remainder half of _float_div_mod): the + adjustment by the divisor when the signs differ, and the divisor-signed + zero remainder. + + Summary of changes: translated from C to C#. fmod is the C# % operator, + copysign(0.0, wx) is a conditional on the divisor's sign, and a zero + divisor raises Sharpy's ZeroDivisionError. + +7. src/Sharpy.Core/NumericText.cs (only NumericText.Normalize) + + Upstream source: CPython 3.14, Objects/unicodeobject.c + + Ported to C#: _PyUnicode_TransformDecimalAndSpaceToASCII (a code point + below 127 kept, a Unicode space made ' ', a decimal digit made its ASCII + digit, anything else made '?'). + + Summary of changes: translated from C to C# over UTF-16 (a surrogate pair + is one code point). The result is a new .NET string, the '?' does not + truncate it, and the whitespace strip that int() and float() apply next + is part of the same method. + +8. src/Sharpy.Core/UnicodeCodec.cs (only the alias table s_aliases) + + Upstream source: CPython 3.15, Lib/encodings/aliases.py + + Taken: the rows of the aliases table whose codec Sharpy implements + (ascii, latin_1, utf_8, utf_8_sig, utf_16, utf_16_le, utf_16_be, utf_32, + utf_32_le and utf_32_be). + + Summary of changes: the rows are a C# Dictionary from the normalized + alias to Sharpy's codec. The encoders and decoders are Sharpy's own. + +9. src/Sharpy.Stdlib/Colorsys/Colorsys.cs + + Upstream source: CPython 3.15, Lib/colorsys.py + + Ported to C#: rgb_to_yiq and yiq_to_rgb (their coefficients), + rgb_to_hsv, hsv_to_rgb, rgb_to_hls (with the gh-106498 denominator), + hls_to_rgb and the helper _v. + + Summary of changes: translated from Python to C# over double. Each + function returns a value tuple, a negative hue left by % is lifted into + [0, 1) explicitly, and yiq_to_rgb's clamps are written as comparisons. + +10. src/Sharpy.Stdlib/Difflib/SequenceMatcher.cs, + src/Sharpy.Stdlib/Difflib/Differ.cs and + src/Sharpy.Stdlib/Difflib/DifflibFunctions.cs + + Upstream source: CPython 3.15, Lib/difflib.py + + Ported to C#: SequenceMatcher (__chain_b with its b2j, junk and popular + sets and the autojunk rule n >= 200, ntest = n // 100 + 1; + find_longest_match with j2len/newj2len and the four junk-extension + loops; get_matching_blocks, get_opcodes, get_grouped_opcodes, ratio, + quick_ratio with fullbcount/avail, and real_quick_ratio); Differ + (compare, _dump, _fancy_replace with its 0.74/0.75 cutoffs, the eqi/eqj + fallback and the intraline tags, and _fancy_helper); and the module + functions unified_diff, context_diff, get_close_matches, ndiff, restore, + IS_LINE_JUNK (its regular expression), IS_CHARACTER_JUNK, + _format_range_unified and _format_range_context. + + Summary of changes: translated from Python to C#. SequenceMatcher is a + generic class over IList, opcodes are value tuples, the work queue is + a list used as a stack, and the generators are C# iterators. Differ + compares lines as char sequences and emits its '?' guide lines without + _qformat's whitespace keeping. get_close_matches sorts its (score, word) + pairs instead of using heapq.nlargest, and errors are raised as Sharpy's + ValueError. + +11. src/Sharpy.Stdlib/Fractions/Fraction.cs (only LimitDenominator) + + Upstream source: CPython 3.15, Lib/fractions.py + + Ported to C#: the continued-fraction loop of Fraction.limit_denominator + (p0, q0, p1, q1, a, q2, k, bound1, bound2) and its error message. + + Summary of changes: translated from Python to C# over + System.Numerics.BigInteger. The two bounds are compared by + cross-multiplied distances instead of CPython's single + 2*d*(q0+k*q1) <= denominator test. + +12. src/Sharpy.Stdlib/Threading/Barrier.cs + + Upstream source: CPython 3.15, Lib/threading.py + + Ported to C#: the Barrier class's wait, reset and abort and its helpers + _enter, _release, _wait, _exit and _break, with their four-state machine + (0 filling, 1 draining, -1 resetting, -2 broken) and arrival index. + + Summary of changes: translated from Python to C# on one monitor (a lock + with Monitor.Wait and Monitor.PulseAll) instead of a threading.Condition. + The timeout is a Stopwatch budget, a timeout the CLR cannot represent is + refused before any wait, and the action is an Action delegate. + +13. src/Sharpy.Stdlib/Ipaddress/AddressFormat.cs, + src/Sharpy.Stdlib/Ipaddress/IPv4Address.cs and + src/Sharpy.Stdlib/Ipaddress/IPv6Address.cs + + Upstream source: CPython Lib/ipaddress.py (the tables as of 3.12, + unchanged in 3.15.2) + + Ported to C#: _BaseAddress.__format__ (the '(#?)(_?)([xbnX])' grammar, + 'n' as 'b' for IPv4 and 'x' for IPv6, and the zero padding to the full + address width). Taken: the _IPv4Constants tables _private_networks, + _private_networks_exceptions and _public_network, the _IPv6Constants + tables _private_networks and _private_networks_exceptions, and the + is_private and is_global rules built on them. + + Summary of changes: the format grammar is a hand-written full-match + scanner, the digits and the '_' grouping are produced directly rather + than through format(int, spec), and a refused spec raises Sharpy's + TypeError. The networks are written as (network, prefix) pairs of a + uint or a byte array and tested by masking, not held as network objects. + +14. src/Sharpy.Stdlib/Urllib/UrllibModule.cs (only the scheme lists) + + Upstream source: CPython 3.15, Lib/urllib/parse.py + + Taken: the uses_netloc and uses_params scheme lists. + + Summary of changes: the lists are case-insensitive HashSets, and + uses_netloc omits 'itms-services'. The URL parsing code around them is + Sharpy's own. + +15. src/Sharpy.Stdlib/spy/fnmatch_module.spy and the C# generated from it, + src/Sharpy.Stdlib/Fnmatch/FnmatchModule.cs + + Upstream source: CPython 3.15, Lib/fnmatch.py + + Ported to Sharpy: translate (the bracket scan with its i, j and stuff + variables, the '!' and ']' look-ahead, the backslash doubling, the '!' + negation, and the \A(?s:...)\Z wrapping). + + Summary of changes: translated from Python to Sharpy over + System.Text.RegularExpressions. Runs of '*' are not compressed, '-' + ranges are passed through unchecked, and fnmatch and filter fold case on + Windows only. + +16. src/Sharpy.Stdlib/spy/itertools.spy and the C# generated from it, + src/Sharpy.Stdlib/Itertools/Itertools.cs + + Upstream source: the "roughly equivalent to" Python code in CPython 3.14, + Doc/library/itertools.rst. (Code in CPython's documentation is dual + licensed under the PSF License Version 2 and the Zero-Clause BSD + license; it is listed here under the former.) + + Ported to Sharpy: combinations, permutations (its indices and cycles + algorithm) and combinations_with_replacement. + + Summary of changes: translated from Python to Sharpy with explicit while + loops. Each result is a list rather than a tuple, and every result is + collected before the first is yielded. + +17. src/Sharpy.Stdlib/spy/os_module.spy and the C# generated from it, + src/Sharpy.Stdlib/Os/Os.cs + + Upstream source: CPython 3.15, Lib/os.py + + Ported to Sharpy: makedirs (the head/tail recursion and the curdir + check) and walk's traversal order (pop a directory, yield it, push its + subdirectories reversed). + + Summary of changes: translated from Python to Sharpy over System.IO. + There is no mode or parent_mode, exist_ok is checked before mkdir rather + than after it fails, and walk is top-down only, with no onerror or + followlinks. + +18. src/Sharpy.Stdlib/spy/shutil_module.spy and the C# generated from it, + src/Sharpy.Stdlib/Shutil/Shutil.cs + + Upstream source: CPython 3.15, Lib/shutil.py + + Ported to Sharpy: move (into an existing directory, then rename, then + the copy-and-remove fallback with its _destinsrc refusal), _basename and + _destinsrc, and copytree's order of steps. + + Summary of changes: translated from Python to Sharpy over System.IO. + There is no copy_function, symlink or ignore handling, and errors are + raised as Sharpy's OSError family. 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/regenerate_spy_stdlib.sh b/build_tools/regenerate_spy_stdlib.sh index a2693c5e72..73d8c243d2 100755 --- a/build_tools/regenerate_spy_stdlib.sh +++ b/build_tools/regenerate_spy_stdlib.sh @@ -136,6 +136,13 @@ for entry in "${MODULES[@]}"; do header_cmd="sharpyc emit csharp src/Sharpy.Stdlib/spy/${emitted_name}.spy -t library -n Sharpy" header="// Generated from src/Sharpy.Stdlib/spy/${emitted_name}.spy — do not edit directly. // To regenerate: $header_cmd" + # The .spy's leading `#` comment block (a CPython licence notice, #2602) is carried into the + # generated C# as `//` lines: the compiler drops comments, and the shipped C# is the derived work. + spy_notice="$(awk '/^#/ { sub(/^#/, "//"); print; next } { exit }' "$SPY_DIR/${emitted_name}.spy")" + if [[ -n "$spy_notice" ]]; then + header="$header +$spy_notice" + fi # Post-process: normalize CRLF→LF, strip trailing whitespace, strip [SharpyModule] # (the hand-written partial carries the python-named one), rename the module in every diff --git a/build_tools/tests/test_third_party_notices.py b/build_tools/tests/test_third_party_notices.py index 1a12ebb4aa..46ca6aba05 100644 --- a/build_tools/tests/test_third_party_notices.py +++ b/build_tools/tests/test_third_party_notices.py @@ -12,10 +12,18 @@ header lines and is listed in the notices file, unless it is in ``EXEMPT`` with a reason; * every file the notices list exists and carries the header, and every file carrying the header is listed (the two places cannot drift apart); -* the licence text at the end of the notices file is the CPython 3.15.2 ``LICENSE.txt``, byte for byte. - -The guard only catches files that declare themselves ports; a port that makes no such claim (a -structural port with no comment saying so) needs the #2602 audit, not this test. +* the licence text at the end of the notices file is the CPython 3.15.2 ``LICENSE.txt``, byte for byte; +* every listed file has a numbered entry (derived portions, clause-3 changes), and every entry names + only listed files; +* ``STDLIB_CENSUS`` holds the #2602 audit's verdict for every Sharpy.Stdlib module with a CPython + 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), a ``port`` module has a noticed file, and a + ``behaviour`` module has none. + +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 +module. A Core file is not a module and is not in the census: its notice rests on the claim scan and on +review. A file that only follows CPython's behaviour should say so ("matching", "the rule of"), not "port": the word is a licence claim. Do not reword a comment to get past this test if the code is a port. @@ -25,6 +33,7 @@ import hashlib import re +import sys from pathlib import Path from typing import Dict, Iterable, List, Set @@ -245,3 +254,252 @@ def test_licence_text_is_the_cpython_file(): data = NOTICES.read_bytes() tail = b"".join(data.splitlines(keepends=True)[-LICENSE_LINES:]) assert hashlib.sha256(tail).hexdigest() == LICENSE_SHA256 + + +# ---- Numbered entries: every listed file has its portions and changes written down ---- + +_ENTRY_START = re.compile(r"^\d+\. ") +_ENTRY_PATH = re.compile(r"src/\S+?\.(?:cs|spy)\b") + + +def entry_files(notices: str) -> Set[str]: + """The paths named in the headings of the numbered entries (a heading runs to its blank line).""" + named: Set[str] = set() + heading: List[str] = [] + for line in notices.splitlines(): + if _ENTRY_START.match(line): + heading = [line] + elif heading and line.strip(): + heading.append(line) + elif heading: + named.update(_ENTRY_PATH.findall(" ".join(heading))) + heading = [] + return named + + +def test_every_listed_file_has_an_entry(): + notices = NOTICES.read_text(encoding="utf-8") + listed = listed_files(notices) + named = entry_files(notices) + problems = [ + f"{rel}: listed but has no numbered entry" for rel in sorted(listed - named) + ] + problems += [ + f"{rel}: has an entry but is not listed" for rel in sorted(named - listed) + ] + assert not problems, "\n".join(problems) + + +# ---- The #2602 census: every Stdlib module with a CPython namesake, read against its source ---- + +STDLIB = "src/Sharpy.Stdlib" + +# Module directory -> the #2602 audit's verdict. "port": code translated from CPython (same +# decomposition, names, constants, regexes or tables), so the module carries the PSF notice (header +# lines + a THIRD-PARTY-NOTICES.txt entry). "behaviour": the same semantics, independently written +# (over .NET, or a different algorithm); matching CPython's error messages or output format alone is +# behaviour. Read against CPython 3.15.2's Lib (and 3.14.0's C sources and Doc/) in November 2026. +# A new module is red here until it is read the same way: add its row, never a blanket default. +STDLIB_CENSUS: Dict[str, str] = { + "Argparse": "behaviour", # argparse.py: own parser and help layout + "Base64": "behaviour", # base64.py: System.Convert + textbook base32/base85 loops + "Bisect": "behaviour", # bisect.py: textbook binary search + "Calendar": "behaviour", # calendar.py: System.DateTime; HTMLCalendar emits CPython's markup + "Collections": "behaviour", # collections/__init__.py: wrappers over Sharpy Dict/List + "Colorsys": "port", # colorsys.py: every function, its names and YIQ coefficients + "Configparser": "behaviour", # configparser.py: own line parser; exception messages match + "Csv": "behaviour", # _csv.c: own quote state machine + "Datetime": "port", # _datetimemodule.c: DatetimeIso.cs (fromisoformat parsers) + "Difflib": "port", # difflib.py: SequenceMatcher, Differ, the diff functions + "Email": "behaviour", # email package: own header/body split + "Fnmatch": "port", # fnmatch.py: translate's bracket scan (spy source + generated C#) + "Fractions": "port", # fractions.py: Fraction.Format.cs, Fraction.cs limit_denominator + "Functools": "behaviour", # functools.py: reduce loop, own LRU cache + "Glob": "behaviour", # glob.py: Directory enumeration + own pattern regex + "Gzip": "behaviour", # gzip.py: System.IO.Compression + "Hashlib": "behaviour", # hashlib.py: System.Security.Cryptography + "Heapq": "behaviour", # heapq.py: textbook sift loops; merge is an own k-way heap + "Hmac": "behaviour", # hmac.py: System.Security.Cryptography + "Html": "behaviour", # html/parser.py: own scanner, WebUtility.HtmlDecode + "Http": "behaviour", # http/: HttpClient; HTTPStatus phrases are RFC text + "Io": "behaviour", # io.py: StringIO over StringBuilder + "Ipaddress": "port", # ipaddress.py: __format__, _private_networks tables (borderline) + "Itertools": "port", # Doc/library/itertools.rst: combinatorics equivalents (borderline) + "Json": "behaviour", # json/: own recursive-descent parser and emitter + "Logging": "behaviour", # logging/: minimal Logger + "Math": "behaviour", # mathmodule.c: System.Math; fsum is Kahan, not msum + "Os": "port", # os.py: makedirs, walk's stack order (borderline) + "Pathlib": "behaviour", # pathlib/: System.IO.Path + "Platform": "behaviour", # platform.py: RuntimeInformation + "Pprint": "behaviour", # pprint.py: own reflection-based layout + "Random": "behaviour", # random.py: System.Random, not Mersenne Twister + "Re": "behaviour", # re/: System.Text.RegularExpressions + pattern translation + "Secrets": "behaviour", # secrets.py: RandomNumberGenerator + "Shlex": "behaviour", # shlex.py: own POSIX split state machine + "Shutil": "port", # shutil.py: move, _basename, _destinsrc (borderline) + "Socket": "behaviour", # socketmodule.c: System.Net.Sockets + "Sqlite3": "behaviour", # _sqlite: Microsoft.Data.Sqlite + "Statistics": "behaviour", # statistics.py: naive float sums, not exact _sum + "String": "behaviour", # string/: the constants only + "Struct": "behaviour", # _struct.c: own format parser over BinaryPrimitives + "Subprocess": "behaviour", # subprocess.py: System.Diagnostics.Process + "Sys": "behaviour", # sys: Environment + "Tarfile": "behaviour", # tarfile.py: System.Formats.Tar + "Tempfile": "behaviour", # tempfile.py: Path.GetRandomFileName + "Textwrap": "behaviour", # textwrap.py: own greedy wrap, not TextWrapper + "Threading": "port", # threading.py: Barrier.cs (ThreadRegistry.cs is behaviour) + "Time": "behaviour", # timemodule.c: Stopwatch/DateTime + "Unittest": "behaviour", # unittest/: xUnit-backed assertions + "Urllib": "port", # urllib/parse.py: uses_netloc/uses_params tables (borderline) + "Uuid": "behaviour", # uuid.py: RFC 4122 over Guid/MD5/SHA1 + "Xml": "behaviour", # xml/etree/: System.Xml.Linq + "Zipfile": "behaviour", # zipfile/: System.IO.Compression.ZipArchive + "Zlib": "behaviour", # zlibmodule.c: System.IO.Compression; textbook CRC32/Adler-32 + "Zoneinfo": "behaviour", # zoneinfo/: TimeZoneInfo +} +VERDICTS = {"port", "behaviour"} + + +def stdlib_modules(root: Path) -> List[str]: + """Module directories under src/Sharpy.Stdlib: a directory holding C# source (not bin/obj).""" + base = root / STDLIB + if not base.is_dir(): + return [] + found = [] + for child in sorted(base.iterdir()): + if not child.is_dir() or child.name in ("bin", "obj"): + continue + if any( + p.is_file() and "bin" not in p.parts and "obj" not in p.parts + for p in child.rglob("*.cs") + ): + found.append(child.name) + return found + + +def namesake_modules(root: Path, stdlib_names: Iterable[str]) -> Set[str]: + names = set(stdlib_names) + return {m for m in stdlib_modules(root) if m.lower() in names} + + +def census_problems( + root: Path, + census: Dict[str, str], + listed: Set[str], + stdlib_names: Iterable[str], +) -> List[str]: + problems = [] + on_disk = namesake_modules(root, stdlib_names) + for module in sorted(on_disk - set(census)): + problems.append( + f"{STDLIB}/{module}: a CPython namesake with no STDLIB_CENSUS row; read it against " + "CPython's source and record 'port' or 'behaviour' (#2602)" + ) + for module in sorted(set(census) - on_disk): + problems.append( + f"{STDLIB}/{module}: in STDLIB_CENSUS but not a namesake module on disk; delete the row" + ) + stdlib_root = root / STDLIB + for module, verdict in sorted(census.items()): + if verdict not in VERDICTS: + problems.append( + f"{module}: verdict {verdict!r} is not one of {sorted(VERDICTS)}" + ) + continue + if module not in on_disk: + continue + headed = sorted( + path.relative_to(root).as_posix() + for path in sources(root) + if stdlib_root in path.parents + and path.relative_to(stdlib_root).parts[0] == module + and _has_header(path.read_text(encoding="utf-8")) + ) + if verdict == "port": + if not headed: + problems.append( + f"{STDLIB}/{module}: verdict 'port' but no file in it carries the PSF header" + ) + for rel in headed: + if rel not in listed: + problems.append( + f"{rel}: in a 'port' module but not listed in THIRD-PARTY-NOTICES.txt" + ) + elif headed: + problems.append( + f"{STDLIB}/{module}: verdict 'behaviour' but {', '.join(headed)} carries the PSF " + "header; the verdict or the header is stale" + ) + return problems + + +def _stdlib_module_names() -> Set[str]: + names = getattr(sys, "stdlib_module_names", None) + if names is None: + pytest.skip( + "sys.stdlib_module_names needs Python 3.10+; the oracle is CPython 3.15" + ) + return set(names) + + +def test_census_positive_control(): + # The census sees the module tree: port modules and a behaviour module are all on disk. + on_disk = namesake_modules(REPO, _stdlib_module_names()) + assert {"Colorsys", "Difflib", "Datetime", "Bisect"} <= on_disk + + +def test_stdlib_census_is_complete_and_honoured(): + listed = listed_files(NOTICES.read_text(encoding="utf-8")) + problems = census_problems(REPO, STDLIB_CENSUS, listed, _stdlib_module_names()) + assert not problems, "\n".join(problems) + + +def _module(tmp_path: Path, name: str, text: str) -> None: + path = tmp_path / STDLIB / name / f"{name}.cs" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +_HEADED = "".join(f"// {line}\n" for line in HEADER_LINES) + "namespace Sharpy { }\n" +_PLAIN = "namespace Sharpy { }\n" + + +def test_census_refuses_an_unread_namesake(tmp_path: Path): + _module(tmp_path, "Pickle", _PLAIN) + _module(tmp_path, "Grapheme", _PLAIN) # no CPython namesake: needs no row + problems = census_problems(tmp_path, {}, set(), {"pickle"}) + assert len(problems) == 1 and "Pickle: a CPython namesake" in problems[0], problems + + +def test_census_refuses_a_stale_row(tmp_path: Path): + problems = census_problems(tmp_path, {"Pickle": "behaviour"}, set(), {"pickle"}) + assert len(problems) == 1 and "not a namesake module on disk" in problems[0], ( + problems + ) + + +def test_census_refuses_an_unnoticed_port(tmp_path: Path): + _module(tmp_path, "Pickle", _PLAIN) + problems = census_problems(tmp_path, {"Pickle": "port"}, set(), {"pickle"}) + assert ( + len(problems) == 1 and "no file in it carries the PSF header" in problems[0] + ), problems + + +def test_census_refuses_an_unlisted_port(tmp_path: Path): + _module(tmp_path, "Pickle", _HEADED) + problems = census_problems(tmp_path, {"Pickle": "port"}, set(), {"pickle"}) + assert len(problems) == 1 and "not listed" in problems[0], problems + + +def test_census_refuses_a_headed_behaviour_module(tmp_path: Path): + _module(tmp_path, "Pickle", _HEADED) + listed = {f"{STDLIB}/Pickle/Pickle.cs"} + problems = census_problems(tmp_path, {"Pickle": "behaviour"}, listed, {"pickle"}) + assert len(problems) == 1 and "verdict 'behaviour'" in problems[0], problems + + +def test_census_accepts_a_noticed_port(tmp_path: Path): + _module(tmp_path, "Pickle", _HEADED) + listed = {f"{STDLIB}/Pickle/Pickle.cs"} + assert census_problems(tmp_path, {"Pickle": "port"}, listed, {"pickle"}) == [] diff --git a/src/Sharpy.Core/FloorDiv.cs b/src/Sharpy.Core/FloorDiv.cs index 185e21530c..5162759d14 100644 --- a/src/Sharpy.Core/FloorDiv.cs +++ b/src/Sharpy.Core/FloorDiv.cs @@ -1,3 +1,11 @@ +// Portions of this file are a C# port of CPython's Objects/floatobject.c (CPython 3.14): the +// quotient half of _float_div_mod (float_floor_div), in the double and float overloads of FloorDiv. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from C to C#; copysign(0.0, vx / wx) is a sign-bit test (netstandard2.1 has +// no Math.CopySign), the float overload repeats the algorithm in single precision, and a zero +// divisor is Sharpy's ZeroDivisionError. + namespace Sharpy { public static partial class Builtins diff --git a/src/Sharpy.Core/FloorMod.cs b/src/Sharpy.Core/FloorMod.cs index a67dd57cc6..9e7e014b35 100644 --- a/src/Sharpy.Core/FloorMod.cs +++ b/src/Sharpy.Core/FloorMod.cs @@ -1,3 +1,10 @@ +// Portions of this file are a C# port of CPython's Objects/floatobject.c (CPython 3.14): float_rem +// (the remainder half of _float_div_mod), in the double and float overloads of FloorMod. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from C to C#; fmod is the C# % operator, copysign(0.0, wx) is a conditional +// on the divisor's sign, and a zero divisor is Sharpy's ZeroDivisionError. + namespace Sharpy { public static partial class Builtins diff --git a/src/Sharpy.Core/NumericText.cs b/src/Sharpy.Core/NumericText.cs index eb16a5cb51..4f28b276cf 100644 --- a/src/Sharpy.Core/NumericText.cs +++ b/src/Sharpy.Core/NumericText.cs @@ -1,3 +1,10 @@ +// Portions of this file are a C# port of CPython's Objects/unicodeobject.c (CPython 3.14): +// _PyUnicode_TransformDecimalAndSpaceToASCII, in NumericText.Normalize. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from C to C# over UTF-16 (a surrogate pair is one code point); the result is +// a new .NET string that the '?' sentinel does not truncate, and the strip that follows is fused in. + using System; using System.Globalization; using System.Text; diff --git a/src/Sharpy.Core/PyFormat.cs b/src/Sharpy.Core/PyFormat.cs index f4963fbd20..9d2edc8b3c 100644 --- a/src/Sharpy.Core/PyFormat.cs +++ b/src/Sharpy.Core/PyFormat.cs @@ -1,9 +1,12 @@ -// Portions of this file are a C# port of _PyUnicode_InsertThousandsGrouping, in CPython's C -// implementation (Objects/): only the private method InsertThousandsGrouping below. +// Portions of this file are a C# port of CPython's C implementation: _PyUnicode_InsertThousandsGrouping +// (Objects/), in the private method InsertThousandsGrouping, and the set-up of format_complex_internal +// (Python/formatter_unicode.c, CPython 3.14: the 'r' default type, skip_re/add_parens and the +// imaginary part's sign), in RenderComplex. // Copyright (c) 2001 Python Software Foundation; All Rights Reserved // Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. -// Changes: translated from C to C#; handles only a uniform group size (no locale grouping string); -// builds a .NET string from right to left instead of writing into a preallocated Unicode buffer. +// Changes: translated from C to C#; the grouping handles only a uniform group size (no locale grouping +// string) and builds a .NET string from right to left instead of writing into a preallocated Unicode +// buffer; the complex parts are rendered by Sharpy's own float formatting and padded as one string. using System; using System.Globalization; diff --git a/src/Sharpy.Core/PyFormatSpec.cs b/src/Sharpy.Core/PyFormatSpec.cs index 26c7491540..a8af28d449 100644 --- a/src/Sharpy.Core/PyFormatSpec.cs +++ b/src/Sharpy.Core/PyFormatSpec.cs @@ -1,3 +1,13 @@ +// Portions of this file are a C# port of CPython's Python/formatter_unicode.c (CPython 3.14): +// parse_internal_render_format_spec and get_integer, and the order and text of the refusals of +// format_string_internal, format_long_internal, format_complex_internal and the per-type +// __format__ switches (unknown format code, sign, alternate form, precision, zero padding, '='). +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from C to C#; the parse returns a PyFormatSpec value or a FormatSpecError +// instead of filling an InternalFormatSpec and setting a Python exception, the grouping x type +// check runs in Validate, and the fractional-part separators are not supported. + using System; using System.Globalization; diff --git a/src/Sharpy.Core/UnicodeCodec.cs b/src/Sharpy.Core/UnicodeCodec.cs index 137769136c..456753c659 100644 --- a/src/Sharpy.Core/UnicodeCodec.cs +++ b/src/Sharpy.Core/UnicodeCodec.cs @@ -1,3 +1,10 @@ +// Portions of this file are taken from CPython's Lib/encodings/aliases.py (CPython 3.15): the rows +// of its aliases table whose codec Sharpy implements (ascii, latin_1, utf_8, utf_16, utf_32). +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: the rows are a C# Dictionary from the normalized alias to the codec; the codecs +// themselves are Sharpy's own. + using System; using System.Collections.Generic; using System.Globalization; diff --git a/src/Sharpy.Stdlib/Colorsys/Colorsys.cs b/src/Sharpy.Stdlib/Colorsys/Colorsys.cs index 269dbdaea5..15b1969531 100644 --- a/src/Sharpy.Stdlib/Colorsys/Colorsys.cs +++ b/src/Sharpy.Stdlib/Colorsys/Colorsys.cs @@ -1,3 +1,10 @@ +// Portions of this file are a C# port of CPython's Lib/colorsys.py (CPython 3.15): rgb_to_yiq, +// yiq_to_rgb (its coefficients), rgb_to_hsv, hsv_to_rgb, rgb_to_hls, hls_to_rgb and the helper _v. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to C# over double; each function returns a value tuple; a negative +// hue left by % is lifted into [0, 1) explicitly, and yiq_to_rgb's clamps are written as comparisons. + #nullable enable using System; diff --git a/src/Sharpy.Stdlib/Difflib/Differ.cs b/src/Sharpy.Stdlib/Difflib/Differ.cs index 3139325a24..caa82420e2 100644 --- a/src/Sharpy.Stdlib/Difflib/Differ.cs +++ b/src/Sharpy.Stdlib/Difflib/Differ.cs @@ -1,3 +1,12 @@ +// Portions of this file are a C# port of CPython's Lib/difflib.py (CPython 3.15): Differ.compare, +// _dump, _fancy_replace (its 0.74/0.75 cutoffs, the eqi/eqj fallback and the intraline tags) and +// _fancy_helper. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to C# iterators; lines are compared as char sequences through the +// generic SequenceMatcher, and the '?' guide lines are emitted directly (no _qformat whitespace +// keeping). + using System; using System.Collections.Generic; using System.Linq; diff --git a/src/Sharpy.Stdlib/Difflib/DifflibFunctions.cs b/src/Sharpy.Stdlib/Difflib/DifflibFunctions.cs index 5f1a4d512d..4684eff6fe 100644 --- a/src/Sharpy.Stdlib/Difflib/DifflibFunctions.cs +++ b/src/Sharpy.Stdlib/Difflib/DifflibFunctions.cs @@ -1,3 +1,11 @@ +// Portions of this file are a C# port of CPython's Lib/difflib.py (CPython 3.15): unified_diff, +// context_diff, get_close_matches, ndiff, restore, IS_LINE_JUNK (its regular expression), +// IS_CHARACTER_JUNK, _format_range_unified and _format_range_context. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to C# iterators over IList; get_close_matches sorts its +// (score, word) pairs instead of using heapq.nlargest, and errors are Sharpy's ValueError. + using System; using System.Collections.Generic; using System.Linq; diff --git a/src/Sharpy.Stdlib/Difflib/SequenceMatcher.cs b/src/Sharpy.Stdlib/Difflib/SequenceMatcher.cs index b198e13e13..4d20d87277 100644 --- a/src/Sharpy.Stdlib/Difflib/SequenceMatcher.cs +++ b/src/Sharpy.Stdlib/Difflib/SequenceMatcher.cs @@ -1,3 +1,11 @@ +// Portions of this file are a C# port of CPython's Lib/difflib.py (CPython 3.15): SequenceMatcher's +// __chain_b, find_longest_match, get_matching_blocks, get_opcodes, get_grouped_opcodes, ratio, +// quick_ratio and real_quick_ratio. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to C# as a generic class over IList; the junk and popular sets +// are HashSets, the work queue is a list used as a stack, and opcodes are value tuples. + using System; using System.Collections.Generic; using System.Linq; diff --git a/src/Sharpy.Stdlib/Fnmatch/FnmatchModule.cs b/src/Sharpy.Stdlib/Fnmatch/FnmatchModule.cs index 29c810d235..0c008f0413 100644 --- a/src/Sharpy.Stdlib/Fnmatch/FnmatchModule.cs +++ b/src/Sharpy.Stdlib/Fnmatch/FnmatchModule.cs @@ -1,5 +1,12 @@ // Generated from src/Sharpy.Stdlib/spy/fnmatch_module.spy — do not edit directly. // To regenerate: sharpyc emit csharp src/Sharpy.Stdlib/spy/fnmatch_module.spy -t library -n Sharpy +// Portions of this file are a Sharpy port of CPython's Lib/fnmatch.py (CPython 3.15): translate +// (its bracket scan with the i/j/stuff variables, the backslash doubling, the '!' negation and the +// \A(?s:...)\Z wrapping). +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to Sharpy over System.Text.RegularExpressions; '*' runs are not +// compressed, '-' ranges are passed through unchecked, and fnmatch/filter fold case on Windows only. #nullable enable using System; diff --git a/src/Sharpy.Stdlib/Fractions/Fraction.cs b/src/Sharpy.Stdlib/Fractions/Fraction.cs index a809afe5b5..83782e7787 100644 --- a/src/Sharpy.Stdlib/Fractions/Fraction.cs +++ b/src/Sharpy.Stdlib/Fractions/Fraction.cs @@ -1,3 +1,10 @@ +// Portions of this file are a C# port of CPython's Lib/fractions.py (CPython 3.15): the +// continued-fraction loop of Fraction.limit_denominator and its error message. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to C# over System.Numerics.BigInteger; the two bounds are compared +// by cross-multiplied distances instead of CPython's single 2*d*(q0+k*q1) test. + using System; using System.Globalization; using System.Numerics; diff --git a/src/Sharpy.Stdlib/Ipaddress/AddressFormat.cs b/src/Sharpy.Stdlib/Ipaddress/AddressFormat.cs index d338303e8e..33f0ffb9fb 100644 --- a/src/Sharpy.Stdlib/Ipaddress/AddressFormat.cs +++ b/src/Sharpy.Stdlib/Ipaddress/AddressFormat.cs @@ -1,3 +1,12 @@ +// Portions of this file are a C# port of CPython's Lib/ipaddress.py (CPython 3.15): +// _BaseAddress.__format__ (the '(#?)(_?)([xbnX])' grammar, the 'n' default per version and the +// full-width zero padding). +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to C#; the regular expression is a hand-written full-match +// scanner, the digits and the '_' grouping are produced directly instead of through +// format(int, spec), and a refused spec is Sharpy's TypeError. + using System; using System.Numerics; using System.Text; diff --git a/src/Sharpy.Stdlib/Ipaddress/IPv4Address.cs b/src/Sharpy.Stdlib/Ipaddress/IPv4Address.cs index 23931123f3..195d4b1972 100644 --- a/src/Sharpy.Stdlib/Ipaddress/IPv4Address.cs +++ b/src/Sharpy.Stdlib/Ipaddress/IPv4Address.cs @@ -1,3 +1,11 @@ +// Portions of this file are taken from CPython's Lib/ipaddress.py (CPython 3.12, unchanged in +// 3.15): the _IPv4Constants tables _private_networks, _private_networks_exceptions and +// _public_network, and the is_private/is_global rule built on them. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: the networks are written as (uint network, prefix) pairs and tested by masking instead +// of being IPv4Network objects. + using System; using System.Net; using System.Net.Sockets; diff --git a/src/Sharpy.Stdlib/Ipaddress/IPv6Address.cs b/src/Sharpy.Stdlib/Ipaddress/IPv6Address.cs index a04b21f93f..042b8117f0 100644 --- a/src/Sharpy.Stdlib/Ipaddress/IPv6Address.cs +++ b/src/Sharpy.Stdlib/Ipaddress/IPv6Address.cs @@ -1,3 +1,11 @@ +// Portions of this file are taken from CPython's Lib/ipaddress.py (CPython 3.12, unchanged in +// 3.15): the _IPv6Constants tables _private_networks and _private_networks_exceptions, and the +// is_private rule built on them. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: the networks are written as (byte[] network, prefix) pairs and tested by masking +// instead of being IPv6Network objects. + using System; using System.Net; using System.Net.Sockets; diff --git a/src/Sharpy.Stdlib/Itertools/Itertools.cs b/src/Sharpy.Stdlib/Itertools/Itertools.cs index fcd470ad7a..285649b852 100644 --- a/src/Sharpy.Stdlib/Itertools/Itertools.cs +++ b/src/Sharpy.Stdlib/Itertools/Itertools.cs @@ -1,5 +1,12 @@ // Generated from src/Sharpy.Stdlib/spy/itertools.spy — do not edit directly. // To regenerate: sharpyc emit csharp src/Sharpy.Stdlib/spy/itertools.spy -t library -n Sharpy +// Portions of this file are a Sharpy port of the pure-Python equivalents in CPython's +// Doc/library/itertools.rst (CPython 3.14): combinations, permutations (its indices/cycles +// algorithm) and combinations_with_replacement. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to Sharpy with explicit while loops; each result is a list, and +// all results are collected before the first is yielded. #nullable enable using System; diff --git a/src/Sharpy.Stdlib/Os/Os.cs b/src/Sharpy.Stdlib/Os/Os.cs index 78051d96a4..1767e508a8 100644 --- a/src/Sharpy.Stdlib/Os/Os.cs +++ b/src/Sharpy.Stdlib/Os/Os.cs @@ -1,5 +1,12 @@ // Generated from src/Sharpy.Stdlib/spy/os_module.spy — do not edit directly. // To regenerate: sharpyc emit csharp src/Sharpy.Stdlib/spy/os_module.spy -t library -n Sharpy +// Portions of this file are a Sharpy port of CPython's Lib/os.py (CPython 3.15): makedirs (the +// head/tail recursion and the curdir check) and walk's stack order (pop a directory, yield it, push +// its subdirectories reversed). +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to Sharpy over System.IO; no mode or parent_mode, exist_ok is +// checked before mkdir, and walk is top-down only with no onerror or followlinks. #nullable enable using System; diff --git a/src/Sharpy.Stdlib/Shutil/Shutil.cs b/src/Sharpy.Stdlib/Shutil/Shutil.cs index 6a930e0597..632510ad60 100644 --- a/src/Sharpy.Stdlib/Shutil/Shutil.cs +++ b/src/Sharpy.Stdlib/Shutil/Shutil.cs @@ -1,5 +1,11 @@ // Generated from src/Sharpy.Stdlib/spy/shutil_module.spy — do not edit directly. // To regenerate: sharpyc emit csharp src/Sharpy.Stdlib/spy/shutil_module.spy -t library -n Sharpy +// Portions of this file are a Sharpy port of CPython's Lib/shutil.py (CPython 3.15): move (the +// rename-then-copy fallback), _basename and _destinsrc, and copytree's order of steps. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to Sharpy over System.IO; no copy_function, symlink or +// ignore handling, and errors are Sharpy's OSError family. #nullable enable using System; diff --git a/src/Sharpy.Stdlib/Threading/Barrier.cs b/src/Sharpy.Stdlib/Threading/Barrier.cs index d94ee8c414..62474f22a9 100644 --- a/src/Sharpy.Stdlib/Threading/Barrier.cs +++ b/src/Sharpy.Stdlib/Threading/Barrier.cs @@ -1,3 +1,11 @@ +// Portions of this file are a C# port of CPython's Lib/threading.py (CPython 3.15): the Barrier +// class's wait, reset and abort and its helpers _enter, _release, _wait, _exit and _break, with +// their four-state machine (0 filling, 1 draining, -1 resetting, -2 broken). +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: translated from Python to C# on one monitor (lock with Monitor.Wait/PulseAll) instead of +// a threading.Condition; the timeout is a Stopwatch budget, and the action is an Action delegate. + using System; using System.Diagnostics; using System.Threading; diff --git a/src/Sharpy.Stdlib/Urllib/UrllibModule.cs b/src/Sharpy.Stdlib/Urllib/UrllibModule.cs index d7d8311b37..0271a0de60 100644 --- a/src/Sharpy.Stdlib/Urllib/UrllibModule.cs +++ b/src/Sharpy.Stdlib/Urllib/UrllibModule.cs @@ -1,3 +1,10 @@ +// Portions of this file are taken from CPython's Lib/urllib/parse.py (CPython 3.15): the +// uses_netloc and uses_params scheme lists. +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved +// Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +// Changes: the lists are case-insensitive HashSets (uses_netloc without 'itms-services'); the +// parsing code around them is Sharpy's own. + using System; using System.Collections.Generic; using System.Text; diff --git a/src/Sharpy.Stdlib/spy/fnmatch_module.spy b/src/Sharpy.Stdlib/spy/fnmatch_module.spy index 3f7f5bc0fd..4fae73c886 100644 --- a/src/Sharpy.Stdlib/spy/fnmatch_module.spy +++ b/src/Sharpy.Stdlib/spy/fnmatch_module.spy @@ -1,3 +1,11 @@ +# Portions of this file are a Sharpy port of CPython's Lib/fnmatch.py (CPython 3.15): translate +# (its bracket scan with the i/j/stuff variables, the backslash doubling, the '!' negation and the +# \A(?s:...)\Z wrapping). +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +# Changes: translated from Python to Sharpy over System.Text.RegularExpressions; '*' runs are not +# compressed, '-' ranges are passed through unchecked, and fnmatch/filter fold case on Windows only. + """Unix shell-style filename pattern matching.""" from system.text import StringBuilder diff --git a/src/Sharpy.Stdlib/spy/itertools.spy b/src/Sharpy.Stdlib/spy/itertools.spy index cbb6c9d8cc..6f9467495a 100644 --- a/src/Sharpy.Stdlib/spy/itertools.spy +++ b/src/Sharpy.Stdlib/spy/itertools.spy @@ -1,3 +1,11 @@ +# Portions of this file are a Sharpy port of the pure-Python equivalents in CPython's +# Doc/library/itertools.rst (CPython 3.14): combinations, permutations (its indices/cycles +# algorithm) and combinations_with_replacement. +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +# Changes: translated from Python to Sharpy with explicit while loops; each result is a list, and +# all results are collected before the first is yielded. + """Functions creating iterators for efficient looping.""" from system import IEquatable diff --git a/src/Sharpy.Stdlib/spy/os_module.spy b/src/Sharpy.Stdlib/spy/os_module.spy index a04adffd89..15f59dcc7d 100644 --- a/src/Sharpy.Stdlib/spy/os_module.spy +++ b/src/Sharpy.Stdlib/spy/os_module.spy @@ -1,3 +1,11 @@ +# Portions of this file are a Sharpy port of CPython's Lib/os.py (CPython 3.15): makedirs (the +# head/tail recursion and the curdir check) and walk's stack order (pop a directory, yield it, push +# its subdirectories reversed). +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +# Changes: translated from Python to Sharpy over System.IO; no mode or parent_mode, exist_ok is +# checked before mkdir, and walk is top-down only with no onerror or followlinks. + """Miscellaneous operating system interfaces.""" from system.io import Path as IoPath, File, Directory, FileInfo, DirectoryInfo diff --git a/src/Sharpy.Stdlib/spy/shutil_module.spy b/src/Sharpy.Stdlib/spy/shutil_module.spy index ffe85d71ea..5e7f6732ad 100644 --- a/src/Sharpy.Stdlib/spy/shutil_module.spy +++ b/src/Sharpy.Stdlib/spy/shutil_module.spy @@ -1,3 +1,10 @@ +# Portions of this file are a Sharpy port of CPython's Lib/shutil.py (CPython 3.15): move (the +# rename-then-copy fallback), _basename and _destinsrc, and copytree's order of steps. +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. +# Changes: translated from Python to Sharpy over System.IO; no copy_function, symlink or +# ignore handling, and errors are Sharpy's OSError family. + """High-level file operations (copy, move, remove trees).""" from system.io import Path as IoPath, File, Directory, DriveInfo From 3860626d0d92700af679b538851734e596f69b2f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:28:16 +0000 Subject: [PATCH 2/3] build: make the #2602 notices census exact per file Review fixes for PR #2777. STDLIB_CENSUS rows now carry the exact set of headed files a port module holds (paths under src/Sharpy.Stdlib): "Difflib": port( "Difflib/SequenceMatcher.cs", "Difflib/Differ.cs", "Difflib/DifflibFunctions.cs"). census_problems asserts the module's headed set equals the recorded set, so a lost header and an extra one are both red. It also refuses a port row with no files, a behaviour row with files, and a row naming a file outside its module, and it requires each port file to be listed in THIRD-PARTY-NOTICES.txt. New synthetic tests cover a lost header in a multi-file port, an extra header in a port module, and the three row-shape refusals. Mutation records (restored from cp copies, never git): - M4 (the reviewer's): strip SequenceMatcher.cs's whole leading comment block (the "port of" line too, so the claim scan stays silent), its file-list line and its name in entry 10. Red: test_stdlib_census_is_complete_and_honoured, with "Difflib/ SequenceMatcher.cs: in Difflib's port set but carries no PSF header" and "in a 'port' module but not listed" (1 failed, 49 passed). Restored -> 50 passed. - Extra header: put the PSF header lines on Difflib/__Init__.cs (a behaviour file in a port module), add it to the file list and to entry 10. Red: test_stdlib_census_is_complete_and_honoured, with "Difflib/__Init__.cs: carries the PSF header but is not in Difflib's port set" (1 failed, 49 passed). Restored -> 50 passed. Nits: UnicodeCodec.cs's header now names all ten codecs its alias table maps to (utf_8_sig and the _le/_be variants), matching entry 8. PyFormatSpec.cs's summary now says CPython 3.14, as its header does. The notices intro is scoped to the CPython audit. It no longer claims every third-party component is listed. Code or data from other upstreams is outside the audit, and no entry is added for it here. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- THIRD-PARTY-NOTICES.txt | 6 +- build_tools/tests/test_third_party_notices.py | 271 ++++++++++++------ src/Sharpy.Core/PyFormatSpec.cs | 2 +- src/Sharpy.Core/UnicodeCodec.cs | 3 +- 4 files changed, 193 insertions(+), 89 deletions(-) diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 76048d2b8d..d8d0dffc47 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -4,12 +4,14 @@ 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. Each such component is listed below, with the Sharpy +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. +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. CPython diff --git a/build_tools/tests/test_third_party_notices.py b/build_tools/tests/test_third_party_notices.py index 46ca6aba05..ad92ff5ee4 100644 --- a/build_tools/tests/test_third_party_notices.py +++ b/build_tools/tests/test_third_party_notices.py @@ -17,7 +17,8 @@ only listed files; * ``STDLIB_CENSUS`` holds the #2602 audit's verdict for every Sharpy.Stdlib module with a CPython 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), a ``port`` module has a noticed file, and a + 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. The claim scan only catches files that declare themselves ports; a port that makes no such claim (a @@ -35,7 +36,7 @@ import re import sys from pathlib import Path -from typing import Dict, Iterable, List, Set +from typing import Dict, FrozenSet, Iterable, List, Set, Tuple import pytest @@ -300,62 +301,94 @@ def test_every_listed_file_has_an_entry(): # (over .NET, or a different algorithm); matching CPython's error messages or output format alone is # behaviour. Read against CPython 3.15.2's Lib (and 3.14.0's C sources and Doc/) in November 2026. # A new module is red here until it is read the same way: add its row, never a blanket default. -STDLIB_CENSUS: Dict[str, str] = { - "Argparse": "behaviour", # argparse.py: own parser and help layout - "Base64": "behaviour", # base64.py: System.Convert + textbook base32/base85 loops - "Bisect": "behaviour", # bisect.py: textbook binary search - "Calendar": "behaviour", # calendar.py: System.DateTime; HTMLCalendar emits CPython's markup - "Collections": "behaviour", # collections/__init__.py: wrappers over Sharpy Dict/List - "Colorsys": "port", # colorsys.py: every function, its names and YIQ coefficients - "Configparser": "behaviour", # configparser.py: own line parser; exception messages match - "Csv": "behaviour", # _csv.c: own quote state machine - "Datetime": "port", # _datetimemodule.c: DatetimeIso.cs (fromisoformat parsers) - "Difflib": "port", # difflib.py: SequenceMatcher, Differ, the diff functions - "Email": "behaviour", # email package: own header/body split - "Fnmatch": "port", # fnmatch.py: translate's bracket scan (spy source + generated C#) - "Fractions": "port", # fractions.py: Fraction.Format.cs, Fraction.cs limit_denominator - "Functools": "behaviour", # functools.py: reduce loop, own LRU cache - "Glob": "behaviour", # glob.py: Directory enumeration + own pattern regex - "Gzip": "behaviour", # gzip.py: System.IO.Compression - "Hashlib": "behaviour", # hashlib.py: System.Security.Cryptography - "Heapq": "behaviour", # heapq.py: textbook sift loops; merge is an own k-way heap - "Hmac": "behaviour", # hmac.py: System.Security.Cryptography - "Html": "behaviour", # html/parser.py: own scanner, WebUtility.HtmlDecode - "Http": "behaviour", # http/: HttpClient; HTTPStatus phrases are RFC text - "Io": "behaviour", # io.py: StringIO over StringBuilder - "Ipaddress": "port", # ipaddress.py: __format__, _private_networks tables (borderline) - "Itertools": "port", # Doc/library/itertools.rst: combinatorics equivalents (borderline) - "Json": "behaviour", # json/: own recursive-descent parser and emitter - "Logging": "behaviour", # logging/: minimal Logger - "Math": "behaviour", # mathmodule.c: System.Math; fsum is Kahan, not msum - "Os": "port", # os.py: makedirs, walk's stack order (borderline) - "Pathlib": "behaviour", # pathlib/: System.IO.Path - "Platform": "behaviour", # platform.py: RuntimeInformation - "Pprint": "behaviour", # pprint.py: own reflection-based layout - "Random": "behaviour", # random.py: System.Random, not Mersenne Twister - "Re": "behaviour", # re/: System.Text.RegularExpressions + pattern translation - "Secrets": "behaviour", # secrets.py: RandomNumberGenerator - "Shlex": "behaviour", # shlex.py: own POSIX split state machine - "Shutil": "port", # shutil.py: move, _basename, _destinsrc (borderline) - "Socket": "behaviour", # socketmodule.c: System.Net.Sockets - "Sqlite3": "behaviour", # _sqlite: Microsoft.Data.Sqlite - "Statistics": "behaviour", # statistics.py: naive float sums, not exact _sum - "String": "behaviour", # string/: the constants only - "Struct": "behaviour", # _struct.c: own format parser over BinaryPrimitives - "Subprocess": "behaviour", # subprocess.py: System.Diagnostics.Process - "Sys": "behaviour", # sys: Environment - "Tarfile": "behaviour", # tarfile.py: System.Formats.Tar - "Tempfile": "behaviour", # tempfile.py: Path.GetRandomFileName - "Textwrap": "behaviour", # textwrap.py: own greedy wrap, not TextWrapper - "Threading": "port", # threading.py: Barrier.cs (ThreadRegistry.cs is behaviour) - "Time": "behaviour", # timemodule.c: Stopwatch/DateTime - "Unittest": "behaviour", # unittest/: xUnit-backed assertions - "Urllib": "port", # urllib/parse.py: uses_netloc/uses_params tables (borderline) - "Uuid": "behaviour", # uuid.py: RFC 4122 over Guid/MD5/SHA1 - "Xml": "behaviour", # xml/etree/: System.Xml.Linq - "Zipfile": "behaviour", # zipfile/: System.IO.Compression.ZipArchive - "Zlib": "behaviour", # zlibmodule.c: System.IO.Compression; textbook CRC32/Adler-32 - "Zoneinfo": "behaviour", # zoneinfo/: TimeZoneInfo +# +# A port row names its exact headed files (relative to src/Sharpy.Stdlib), and the files in the module +# that carry the PSF header must be exactly that set: a lost header (a ported file that drifted out of +# the notice) and an extra one (a behaviour file in a port module, headed by mistake) are both red. A +# behaviour row's set is empty. A file added to a port module is read like a new module: header and +# row, or neither. +BEHAVIOUR: Tuple[str, FrozenSet[str]] = ("behaviour", frozenset()) + + +def port(*files: str) -> Tuple[str, FrozenSet[str]]: + return ("port", frozenset(files)) + + +STDLIB_CENSUS: Dict[str, Tuple[str, FrozenSet[str]]] = { + "Argparse": BEHAVIOUR, # argparse.py: own parser and help layout + "Base64": BEHAVIOUR, # base64.py: System.Convert + textbook base32/base85 loops + "Bisect": BEHAVIOUR, # bisect.py: textbook binary search + "Calendar": BEHAVIOUR, # calendar.py: System.DateTime; HTMLCalendar emits CPython's markup + "Collections": BEHAVIOUR, # collections/__init__.py: wrappers over Sharpy Dict/List + # colorsys.py: every function, its names and YIQ coefficients + "Colorsys": port("Colorsys/Colorsys.cs"), + "Configparser": BEHAVIOUR, # configparser.py: own line parser; exception messages match + "Csv": BEHAVIOUR, # _csv.c: own quote state machine + # _datetimemodule.c: DatetimeIso.cs (fromisoformat parsers) + "Datetime": port("Datetime/DatetimeIso.cs"), + # difflib.py: SequenceMatcher, Differ, the diff functions + "Difflib": port( + "Difflib/SequenceMatcher.cs", + "Difflib/Differ.cs", + "Difflib/DifflibFunctions.cs", + ), + "Email": BEHAVIOUR, # email package: own header/body split + # fnmatch.py: translate's bracket scan (spy source + generated C#) + "Fnmatch": port("Fnmatch/FnmatchModule.cs"), + # fractions.py: Fraction.Format.cs, Fraction.cs limit_denominator + "Fractions": port("Fractions/Fraction.Format.cs", "Fractions/Fraction.cs"), + "Functools": BEHAVIOUR, # functools.py: reduce loop, own LRU cache + "Glob": BEHAVIOUR, # glob.py: Directory enumeration + own pattern regex + "Gzip": BEHAVIOUR, # gzip.py: System.IO.Compression + "Hashlib": BEHAVIOUR, # hashlib.py: System.Security.Cryptography + "Heapq": BEHAVIOUR, # heapq.py: textbook sift loops; merge is an own k-way heap + "Hmac": BEHAVIOUR, # hmac.py: System.Security.Cryptography + "Html": BEHAVIOUR, # html/parser.py: own scanner, WebUtility.HtmlDecode + "Http": BEHAVIOUR, # http/: HttpClient; HTTPStatus phrases are RFC text + "Io": BEHAVIOUR, # io.py: StringIO over StringBuilder + # ipaddress.py: __format__, _private_networks tables (borderline) + "Ipaddress": port( + "Ipaddress/AddressFormat.cs", + "Ipaddress/IPv4Address.cs", + "Ipaddress/IPv6Address.cs", + ), + # Doc/library/itertools.rst: combinatorics equivalents (borderline) + "Itertools": port("Itertools/Itertools.cs"), + "Json": BEHAVIOUR, # json/: own recursive-descent parser and emitter + "Logging": BEHAVIOUR, # logging/: minimal Logger + "Math": BEHAVIOUR, # mathmodule.c: System.Math; fsum is Kahan, not msum + # os.py: makedirs, walk's stack order (borderline) + "Os": port("Os/Os.cs"), + "Pathlib": BEHAVIOUR, # pathlib/: System.IO.Path + "Platform": BEHAVIOUR, # platform.py: RuntimeInformation + "Pprint": BEHAVIOUR, # pprint.py: own reflection-based layout + "Random": BEHAVIOUR, # random.py: System.Random, not Mersenne Twister + "Re": BEHAVIOUR, # re/: System.Text.RegularExpressions + pattern translation + "Secrets": BEHAVIOUR, # secrets.py: RandomNumberGenerator + "Shlex": BEHAVIOUR, # shlex.py: own POSIX split state machine + # shutil.py: move, _basename, _destinsrc (borderline) + "Shutil": port("Shutil/Shutil.cs"), + "Socket": BEHAVIOUR, # socketmodule.c: System.Net.Sockets + "Sqlite3": BEHAVIOUR, # _sqlite: Microsoft.Data.Sqlite + "Statistics": BEHAVIOUR, # statistics.py: naive float sums, not exact _sum + "String": BEHAVIOUR, # string/: the constants only + "Struct": BEHAVIOUR, # _struct.c: own format parser over BinaryPrimitives + "Subprocess": BEHAVIOUR, # subprocess.py: System.Diagnostics.Process + "Sys": BEHAVIOUR, # sys: Environment + "Tarfile": BEHAVIOUR, # tarfile.py: System.Formats.Tar + "Tempfile": BEHAVIOUR, # tempfile.py: Path.GetRandomFileName + "Textwrap": BEHAVIOUR, # textwrap.py: own greedy wrap, not TextWrapper + # threading.py: Barrier.cs (ThreadRegistry.cs is behaviour) + "Threading": port("Threading/Barrier.cs"), + "Time": BEHAVIOUR, # timemodule.c: Stopwatch/DateTime + "Unittest": BEHAVIOUR, # unittest/: xUnit-backed assertions + # urllib/parse.py: uses_netloc/uses_params tables (borderline) + "Urllib": port("Urllib/UrllibModule.cs"), + "Uuid": BEHAVIOUR, # uuid.py: RFC 4122 over Guid/MD5/SHA1 + "Xml": BEHAVIOUR, # xml/etree/: System.Xml.Linq + "Zipfile": BEHAVIOUR, # zipfile/: System.IO.Compression.ZipArchive + "Zlib": BEHAVIOUR, # zlibmodule.c: System.IO.Compression; textbook CRC32/Adler-32 + "Zoneinfo": BEHAVIOUR, # zoneinfo/: TimeZoneInfo } VERDICTS = {"port", "behaviour"} @@ -384,7 +417,7 @@ def namesake_modules(root: Path, stdlib_names: Iterable[str]) -> Set[str]: def census_problems( root: Path, - census: Dict[str, str], + census: Dict[str, Tuple[str, FrozenSet[str]]], listed: Set[str], stdlib_names: Iterable[str], ) -> List[str]: @@ -400,36 +433,60 @@ def census_problems( f"{STDLIB}/{module}: in STDLIB_CENSUS but not a namesake module on disk; delete the row" ) stdlib_root = root / STDLIB - for module, verdict in sorted(census.items()): + for module, (verdict, recorded) in sorted(census.items()): if verdict not in VERDICTS: problems.append( f"{module}: verdict {verdict!r} is not one of {sorted(VERDICTS)}" ) continue + if verdict == "port" and not recorded: + problems.append( + f"{module}: verdict 'port' but the row names no headed file" + ) + if verdict == "behaviour" and recorded: + problems.append( + f"{module}: verdict 'behaviour' but the row names files " + f"{sorted(recorded)}; a behaviour row's set is empty" + ) + continue + for rel in sorted(recorded): + if Path(rel).parts[0] != module: + problems.append( + f"{module}: the row names {rel}, which is not in the module" + ) if module not in on_disk: continue - headed = sorted( - path.relative_to(root).as_posix() + headed = { + path.relative_to(stdlib_root).as_posix() for path in sources(root) if stdlib_root in path.parents and path.relative_to(stdlib_root).parts[0] == module and _has_header(path.read_text(encoding="utf-8")) - ) - if verdict == "port": - if not headed: + } + if verdict == "behaviour": + if headed: problems.append( - f"{STDLIB}/{module}: verdict 'port' but no file in it carries the PSF header" + f"{STDLIB}/{module}: verdict 'behaviour' but " + f"{', '.join(sorted(headed))} carries the PSF header; the verdict or the " + "header is stale" ) - for rel in headed: - if rel not in listed: - problems.append( - f"{rel}: in a 'port' module but not listed in THIRD-PARTY-NOTICES.txt" - ) - elif headed: + continue + for rel in sorted(recorded - headed): + problems.append( + f"{STDLIB}/{rel}: in {module}'s port set but carries no PSF header (lost " + "header, or a stale row)" + ) + for rel in sorted(headed - recorded): problems.append( - f"{STDLIB}/{module}: verdict 'behaviour' but {', '.join(headed)} carries the PSF " - "header; the verdict or the header is stale" + f"{STDLIB}/{rel}: carries the PSF header but is not in {module}'s port set; " + "record it if it is a port, else drop the header" ) + for rel in sorted(recorded | headed): + if f"{STDLIB}/{rel}" not in listed: + problems.append( + f"{STDLIB}/{rel}: in a 'port' module but not listed in " + "THIRD-PARTY-NOTICES.txt" + ) return problems @@ -454,14 +511,16 @@ def test_stdlib_census_is_complete_and_honoured(): assert not problems, "\n".join(problems) -def _module(tmp_path: Path, name: str, text: str) -> None: - path = tmp_path / STDLIB / name / f"{name}.cs" +def _module(tmp_path: Path, name: str, text: str, file: str = "") -> None: + path = tmp_path / STDLIB / name / (file or f"{name}.cs") path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") _HEADED = "".join(f"// {line}\n" for line in HEADER_LINES) + "namespace Sharpy { }\n" _PLAIN = "namespace Sharpy { }\n" +_PICKLE = "Pickle/Pickle.cs" +_LISTED = {f"{STDLIB}/{_PICKLE}"} def test_census_refuses_an_unread_namesake(tmp_path: Path): @@ -472,34 +531,76 @@ def test_census_refuses_an_unread_namesake(tmp_path: Path): def test_census_refuses_a_stale_row(tmp_path: Path): - problems = census_problems(tmp_path, {"Pickle": "behaviour"}, set(), {"pickle"}) + problems = census_problems(tmp_path, {"Pickle": BEHAVIOUR}, set(), {"pickle"}) assert len(problems) == 1 and "not a namesake module on disk" in problems[0], ( problems ) +def test_census_refuses_a_port_row_with_no_files(tmp_path: Path): + _module(tmp_path, "Pickle", _PLAIN) + problems = census_problems(tmp_path, {"Pickle": port()}, set(), {"pickle"}) + assert len(problems) == 1 and "names no headed file" in problems[0], problems + + +def test_census_refuses_a_behaviour_row_with_files(tmp_path: Path): + _module(tmp_path, "Pickle", _PLAIN) + census = {"Pickle": ("behaviour", frozenset({_PICKLE}))} + problems = census_problems(tmp_path, census, set(), {"pickle"}) + assert len(problems) == 1 and "set is empty" in problems[0], problems + + +def test_census_refuses_a_row_naming_another_module(tmp_path: Path): + _module(tmp_path, "Pickle", _HEADED) + census = {"Pickle": port(_PICKLE, "Shelve/Shelve.cs")} + problems = census_problems(tmp_path, census, _LISTED, {"pickle"}) + assert any("not in the module" in p for p in problems), problems + + def test_census_refuses_an_unnoticed_port(tmp_path: Path): _module(tmp_path, "Pickle", _PLAIN) - problems = census_problems(tmp_path, {"Pickle": "port"}, set(), {"pickle"}) - assert ( - len(problems) == 1 and "no file in it carries the PSF header" in problems[0] + census = {"Pickle": port(_PICKLE)} + problems = census_problems(tmp_path, census, _LISTED, {"pickle"}) + assert len(problems) == 1 and "carries no PSF header" in problems[0], problems + + +def test_census_refuses_a_lost_header_in_a_multi_file_port(tmp_path: Path): + # The per-module census missed this: one file of a port module losing its header (and its + # notice lines) while a sibling keeps one. + _module(tmp_path, "Pickle", _HEADED) + _module(tmp_path, "Pickle", _PLAIN, "Unpickler.cs") + census = {"Pickle": port(_PICKLE, "Pickle/Unpickler.cs")} + problems = census_problems(tmp_path, census, _LISTED, {"pickle"}) + assert any( + "Pickle/Unpickler.cs: in Pickle's port set but carries no PSF header" in p + for p in problems ), problems +def test_census_refuses_an_extra_header_in_a_port_module(tmp_path: Path): + _module(tmp_path, "Pickle", _HEADED) + _module(tmp_path, "Pickle", _HEADED, "Registry.cs") + listed = _LISTED | {f"{STDLIB}/Pickle/Registry.cs"} + problems = census_problems(tmp_path, {"Pickle": port(_PICKLE)}, listed, {"pickle"}) + assert len(problems) == 1 and "not in Pickle's port set" in problems[0], problems + + def test_census_refuses_an_unlisted_port(tmp_path: Path): _module(tmp_path, "Pickle", _HEADED) - problems = census_problems(tmp_path, {"Pickle": "port"}, set(), {"pickle"}) + problems = census_problems(tmp_path, {"Pickle": port(_PICKLE)}, set(), {"pickle"}) assert len(problems) == 1 and "not listed" in problems[0], problems def test_census_refuses_a_headed_behaviour_module(tmp_path: Path): _module(tmp_path, "Pickle", _HEADED) - listed = {f"{STDLIB}/Pickle/Pickle.cs"} - problems = census_problems(tmp_path, {"Pickle": "behaviour"}, listed, {"pickle"}) + problems = census_problems(tmp_path, {"Pickle": BEHAVIOUR}, _LISTED, {"pickle"}) assert len(problems) == 1 and "verdict 'behaviour'" in problems[0], problems def test_census_accepts_a_noticed_port(tmp_path: Path): _module(tmp_path, "Pickle", _HEADED) - listed = {f"{STDLIB}/Pickle/Pickle.cs"} - assert census_problems(tmp_path, {"Pickle": "port"}, listed, {"pickle"}) == [] + _module( + tmp_path, "Pickle", _PLAIN, "Registry.cs" + ) # a behaviour file in a port module + census = {"Pickle": port(_PICKLE)} + assert census_problems(tmp_path, census, _LISTED, {"pickle"}) == [] diff --git a/src/Sharpy.Core/PyFormatSpec.cs b/src/Sharpy.Core/PyFormatSpec.cs index a8af28d449..0765168542 100644 --- a/src/Sharpy.Core/PyFormatSpec.cs +++ b/src/Sharpy.Core/PyFormatSpec.cs @@ -79,7 +79,7 @@ private FormatSpecError(bool isTypeError, string message) /// [[fill]align][sign][z][#][0][width][grouping][.precision][type] (#1984, R-BX). /// renders from the spec this returns, and the /// compiler's static twin calls the same — so a rule lives in exactly one - /// place. The parse and the rule order are CPython 3.12's Objects/stringlib/unicode_format.h + /// place. The parse and the rule order are CPython 3.14's Objects/stringlib/unicode_format.h /// / Python/formatter_unicode.c: parse_internal_render_format_spec, then the /// per-type __format__ switch, then format_string_internal / /// format_long_internal. diff --git a/src/Sharpy.Core/UnicodeCodec.cs b/src/Sharpy.Core/UnicodeCodec.cs index 456753c659..525fc92d6a 100644 --- a/src/Sharpy.Core/UnicodeCodec.cs +++ b/src/Sharpy.Core/UnicodeCodec.cs @@ -1,5 +1,6 @@ // Portions of this file are taken from CPython's Lib/encodings/aliases.py (CPython 3.15): the rows -// of its aliases table whose codec Sharpy implements (ascii, latin_1, utf_8, utf_16, utf_32). +// of its aliases table whose codec Sharpy implements (ascii, latin_1, utf_8, utf_8_sig, utf_16, +// utf_16_le, utf_16_be, utf_32, utf_32_le and utf_32_be). // Copyright (c) 2001 Python Software Foundation; All Rights Reserved // Licensed under the PSF License Version 2; see THIRD-PARTY-NOTICES.txt at the repository root. // Changes: the rows are a C# Dictionary from the normalized alias to the codec; the codecs From e18faf213ff04e927807b38aca09f577b7532dba Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:41:18 +0000 Subject: [PATCH 3/3] build: say what the notices census enforces Second-review fix for PR #2777. The census comment claimed a file added to a port module is read like a new module, "header and row, or neither". It is not enforced. The census sees only headed files, so a new unheaded file in a port module stays green, and so does a row edited together with its header. The comment now says what is enforced: a port module's headed files equal its row's set, an unheaded file is not seen, and the row is the audit's record that review reads. census_problems also checks a row's shape before unpacking it. A bare "port", port(""), a 1-tuple or a list set now gets a named problem ("is not (verdict, set of file paths)") instead of a ValueError or IndexError, covered by test_census_names_a_malformed_row. Mutation: replaced the shape check's condition with "True or ..." so it never fires. Red: the 4 test_census_names_a_malformed_row cases (4 failed, 50 passed). Restored from a cp copy: 54 passed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/tests/test_third_party_notices.py | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/build_tools/tests/test_third_party_notices.py b/build_tools/tests/test_third_party_notices.py index ad92ff5ee4..67fae0c9f9 100644 --- a/build_tools/tests/test_third_party_notices.py +++ b/build_tools/tests/test_third_party_notices.py @@ -305,8 +305,9 @@ def test_every_listed_file_has_an_entry(): # A port row names its exact headed files (relative to src/Sharpy.Stdlib), and the files in the module # that carry the PSF header must be exactly that set: a lost header (a ported file that drifted out of # the notice) and an extra one (a behaviour file in a port module, headed by mistake) are both red. A -# behaviour row's set is empty. A file added to a port module is read like a new module: header and -# row, or neither. +# behaviour row's set is empty. What is enforced is that equality, nothing more: a file without the +# header is not seen, so a new unheaded file in a port module stays green, and so does a row edited +# together with its header. The row is the audit's record; review reads it. BEHAVIOUR: Tuple[str, FrozenSet[str]] = ("behaviour", frozenset()) @@ -433,7 +434,19 @@ def census_problems( f"{STDLIB}/{module}: in STDLIB_CENSUS but not a namesake module on disk; delete the row" ) stdlib_root = root / STDLIB - for module, (verdict, recorded) in sorted(census.items()): + for module, row in sorted(census.items()): + if not ( + isinstance(row, tuple) + and len(row) == 2 + and isinstance(row[1], (set, frozenset)) + and all(isinstance(rel, str) and rel for rel in row[1]) + ): + problems.append( + f"{module}: row {row!r} is not (verdict, set of file paths); " + "use BEHAVIOUR or port(...)" + ) + continue + verdict, recorded = row if verdict not in VERDICTS: problems.append( f"{module}: verdict {verdict!r} is not one of {sorted(VERDICTS)}" @@ -604,3 +617,12 @@ def test_census_accepts_a_noticed_port(tmp_path: Path): ) # a behaviour file in a port module census = {"Pickle": port(_PICKLE)} assert census_problems(tmp_path, census, _LISTED, {"pickle"}) == [] + + +@pytest.mark.parametrize("row", ["port", port(""), ("port",), ("port", [_PICKLE])]) +def test_census_names_a_malformed_row(tmp_path: Path, row): + _module(tmp_path, "Pickle", _HEADED) + problems = census_problems(tmp_path, {"Pickle": row}, _LISTED, {"pickle"}) + assert ( + len(problems) == 1 and "is not (verdict, set of file paths)" in problems[0] + ), problems