Files
youknowdotandJeong, YunWon 06007c81fa Begin the Python 3.15 target and essential-library migration (#8950)
* Target Python 3.15 using the final upstream reference

Update active version and comparison configuration to Python 3.15.0. Preserve the alpha implementation status, actual bytecode format, and existing libraries pending separate migration. Align generated library-upgrade workflow pins without changing permissions or actions.

Assisted-by: OpenAI Codex:model identifier unavailable

* Adapt essential snippet contracts to Python 3.15 final

Preserve existing coverage while following verified final behavior for script metadata, builtin signatures and loading, AST fixture construction, memoryview diagnostics, mmap search bounds, and struct format errors. The unchanged final comparator exposes the earlier expectations; focused native baseline failures establish the required implementation changes.

Assisted-by: OpenAI Codex:model identifier unavailable

* Keep final-reference regression paths and remove expired sysconfig argument

Preserve reverse multiplication syntax and native exact overflow diagnostics. Accept the two source-proven CPython 3.15 specialization messages only in affected reverse str/bytes/tuple cases. Use an actually out-of-range Windows datetime errno fixture. Remove the sysconfig check_home argument at its existing canonical 3.15 removal test boundary.

Assisted-by: OpenAI Codex:model identifier unavailable

* Keep README wording unchanged in Python 3.15 transition

Assisted-by: OpenAI Codex:model identifier unavailable

* Match Python 3.15 repetition specialization and keep universal tests

Use exact sequence-type guards and preserve generic fallback diagnostics. Validate both cold and warmed expressions without implementation-specific assertions. Reject stale CPython source checkouts and cross-version library caches.

Assisted-by: OpenAI Codex:model identifier unavailable

* Limit in-place specialization additions to exact sequence repetition

Assisted-by: OpenAI Codex:model identifier unavailable

* Keep subclass regression scoped to repetition dispatch

Assisted-by: OpenAI Codex:model identifier unavailable

* Provision final CPython 3.15 with pinned uv builds

Assisted-by: OpenAI Codex:model identifier unavailable

* Enforce Python 3.15 AST constructor requirements

Reject retired missing-field and arbitrary-keyword forms while preserving defaults and explicit placeholders. Sync only matching final CPython constructor test hunks.

Assisted-by: OpenAI Codex:model identifier unavailable

* Keep seeded Python ahead of its Windows DLL directory

Assisted-by: OpenAI Codex:model identifier unavailable

* Keep opcode metadata tied to the implemented bytecode format

The interpreter target and reference tests use Python 3.15.0, but the current Rust opcode enum retains the 3.14 bytecode format. Generate metadata from its matching source rather than importing unsupported instruction families.

Assisted-by: OpenAI Codex:model identifier unavailable

* Align CSV, logarithm and decimal formatting with Python 3.15

Propagate dialect lookup errors except AttributeError, retry integer logarithms after float overflow, and update the decimal conversion diagnostic. Exercise the final reference contracts without implementation-specific branches.

Assisted-by: OpenAI Codex:model identifier unavailable

* Bind the logarithm index result before borrowing its integer

Assisted-by: OpenAI Codex:model identifier unavailable

* Align required canonical test expectations with Python 3.15

Take only demonstrated contract changes from CPython v3.15.0, d220409a13b77de7a6c30abe16ea90db01528edc: removed module __cached__, Struct format exception classes, and decimal-format diagnostic. Preserve unrelated tests and expectations.

Assisted-by: OpenAI Codex:model identifier unavailable

* Track pending frozendict pickle support during the 3.15 transition

Keep the two existing frozendict pickle tests running as expected failures until #8951 supplies the builtin. Unexpected success will signal removal of these temporary markers.

Assisted-by: OpenAI Codex:model identifier unavailable

* Support final Python 3.15 Windows negative timestamps

Use FILETIME for pre-epoch conversions and preserve precise Windows timestamp errors.

Assisted-by: OpenAI Codex:model identifier unavailable

* Derive historical Windows timezone offsets from wall time

FILETIME reports historical DST as unknown, so calculate the actual offset rather than selecting standard-time bias.

Assisted-by: OpenAI Codex:model identifier unavailable

* Identify decimal formatting arguments in Python 3.15 errors

Track consumed positional arguments, including star width and precision, and preserve mapping key representations in decimal conversion diagnostics.

Assisted-by: OpenAI Codex:model identifier unavailable

* Reuse mapping format keys for lookup and error context

Assisted-by: OpenAI Codex:model identifier unavailable

* Borrow mapping diagnostic keys as Python objects

Assisted-by: OpenAI Codex:model identifier unavailable

* Avoid empty components in the reference Python library path

Assisted-by: OpenAI Codex:model identifier unavailable

* Isolate RustPython bytecode caches during the 3.15 transition

Assisted-by: OpenAI Codex:model identifier unavailable

* Sync final Windows timestamp test expectations

Import only the final CPython platform-limit guards and mktime roundtrip expectation required by the existing Windows CI suite.

Assisted-by: OpenAI Codex:model identifier unavailable

* Restore official Python setup for 3.15 final

Use the existing pinned setup-python action now that its official catalog supplies CPython 3.15.0. Remove the temporary standalone provisioning action and its sparse-checkout entry while retaining interpreter outputs and requested versions.

Assisted-by: OpenAI Codex:model identifier unavailable

* Align merged runtime contracts with Python 3.15 final

Restrict mappingproxy ordering, use final codec registry normalization, and prefer index conversion before float conversion for sleep. Retain universal Python assertions and import the matching final codec/time canonical test hunks plus the non-ASCII codec-name deprecation warning.

Upstream source: CPython d220409a13b77de7a6c30abe16ea90db01528edc. The existing codec normalization implementation and bytecode contract remain unchanged.

Assisted-by: OpenAI Codex:model identifier unavailable

* Limit Windows launcher version check to its interpreter

Exclude only the CPython py.exe version-identity case from RustPython CI. The installed launcher reports its own final version, while RustPython correctly remains alpha. Preserve the other 45 launcher cases and all RustPython version assertions without modifying Lib.

Assisted-by: OpenAI Codex:model identifier unavailable

---------

Co-authored-by: Jeong, YunWon <69878+youknowone@users.noreply.github.com>
2026-10-11 12:57:49 +09:00

249 lines
6.7 KiB
Python

#!/usr/bin/env python
import collections
import dataclasses
import pathlib
import re
import subprocess
import urllib.request
import tomllib
CPYTHON_VERSION = "3.15"
CONSTS_PATTERN = re.compile(r"\b_*[A-Z]+(?:_+[A-Z]+)*_*\b")
CARGO_TOML_FILE = pathlib.Path(__file__).parents[1] / "Cargo.toml"
CARGO_TOML = tomllib.loads(CARGO_TOML_FILE.read_text())
LIBC_DATA = CARGO_TOML["workspace"]["dependencies"]["libc"]
LIBC_VERSION = LIBC_DATA["version"] if isinstance(LIBC_DATA, dict) else LIBC_DATA
BASE_URL = f"https://raw.githubusercontent.com/rust-lang/libc/refs/tags/{LIBC_VERSION}"
EXCLUDE = frozenset(
{
# Defined at `vm/src/stdlib/os.rs`
"O_APPEND",
"O_CREAT",
"O_EXCL",
"O_RDONLY",
"O_RDWR",
"O_TRUNC",
"O_WRONLY",
"SEEK_CUR",
"SEEK_END",
"SEEK_SET",
# Functions, not consts
"WCOREDUMP",
"WIFCONTINUED",
"WIFSTOPPED",
"WIFSIGNALED",
"WIFEXITED",
"WEXITSTATUS",
"WSTOPSIG",
"WTERMSIG",
# False positive
# "EOF",
}
)
def rustfmt(code: str) -> str:
return subprocess.check_output(["rustfmt", "--emit=stdout"], input=code, text=True)
@dataclasses.dataclass(eq=True, frozen=True, slots=True)
class Cfg:
inner: str
def __str__(self) -> str:
return self.inner
def __lt__(self, other) -> bool:
si, oi = map(str, (self.inner, other.inner))
# Smaller length cfgs are smaller, regardless of value.
return (len(si), si) < (len(oi), oi)
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
class Target:
cfgs: set[Cfg]
sources: set[str] = dataclasses.field(default_factory=set)
extras: set[str] = dataclasses.field(default_factory=set)
TARGETS = (
Target(
cfgs={Cfg('target_os = "android"')},
sources={
f"{BASE_URL}/src/unix/linux_like/android/mod.rs",
f"{BASE_URL}/libc-test/semver/android.txt",
},
),
Target(
cfgs={Cfg('target_os = "dragonfly"')},
sources={
f"{BASE_URL}/src/unix/bsd/freebsdlike/dragonfly/mod.rs",
f"{BASE_URL}/libc-test/semver/dragonfly.txt",
},
),
Target(
cfgs={Cfg('target_os = "freebsd"')},
sources={
f"{BASE_URL}/src/unix/bsd/freebsdlike/freebsd/mod.rs",
f"{BASE_URL}/libc-test/semver/freebsd.txt",
},
),
Target(
cfgs={Cfg('target_os = "linux"')},
sources={
f"{BASE_URL}/src/unix/linux_like/mod.rs",
f"{BASE_URL}/src/unix/linux_like/linux_l4re_shared.rs",
f"{BASE_URL}/libc-test/semver/linux.txt",
},
),
Target(
cfgs={Cfg('target_os = "macos"')},
sources={
f"{BASE_URL}/src/unix/bsd/apple/mod.rs",
f"{BASE_URL}/libc-test/semver/apple.txt",
},
extras={"COPYFILE_DATA as _COPYFILE_DATA"},
),
Target(
cfgs={Cfg('target_os = "netbsd"')},
sources={
f"{BASE_URL}/src/unix/bsd/netbsdlike/netbsd/mod.rs",
f"{BASE_URL}/libc-test/semver/netbsd.txt",
},
),
Target(
cfgs={Cfg('target_os = "redox"')},
sources={
f"{BASE_URL}/src/unix/redox/mod.rs",
f"{BASE_URL}/libc-test/semver/redox.txt",
},
),
Target(cfgs={Cfg("unix")}, sources={f"{BASE_URL}/libc-test/semver/unix.txt"}),
)
def extract_consts(
contents: str,
*,
pattern: re.Pattern = CONSTS_PATTERN,
exclude: frozenset[str] = EXCLUDE,
) -> frozenset[str]:
"""
Extract all words that are comprised from only uppercase letters + underscores.
Parameters
----------
contents : str
Contents to extract the constants from.
pattern : re.Pattern, Optional
RE compiled pattern for extracting the consts.
exclude : frozenset[str], Optional
Items to exclude from the returned value.
Returns
-------
frozenset[str]
All constant names.
"""
result = frozenset(pattern.findall(contents))
return result - exclude
def consts_from_url(
url: str, *, pattern: re.Pattern = CONSTS_PATTERN, exclude: frozenset[str] = EXCLUDE
) -> frozenset[str]:
"""
Extract all consts from the contents found at the given URL.
Parameters
----------
url : str
URL to fetch the contents from.
pattern : re.Pattern, Optional
RE compiled pattern for extracting the consts.
exclude : frozenset[str], Optional
Items to exclude from the returned value.
Returns
-------
frozenset[str]
All constant names at the URL.
"""
try:
with urllib.request.urlopen(url) as f:
contents = f.read().decode()
except urllib.error.HTTPError as err:
err.add_note(url)
raise
return extract_consts(contents, pattern=pattern, exclude=exclude)
def main():
# Step 1: Get all OS contants that we do want from upstream
wanted_consts = consts_from_url(
f"https://docs.python.org/{CPYTHON_VERSION}/library/os.html",
# TODO: Exclude matches if they have `(` after (those are functions)
pattern=re.compile(r"\bos\.(_*[A-Z]+(?:_+[A-Z]+)*_*)"),
)
# Step 2: build dict of what consts are available per cfg. `cfg -> {consts}`
available = collections.defaultdict(set)
for target in TARGETS:
consts = set()
for source in target.sources:
consts |= consts_from_url(source)
for cfg in target.cfgs:
available[cfg] |= consts
# Step 3: Keep only the "wanted" consts. Build a groupped mapping of `{cfgs} -> {consts}'
groups = collections.defaultdict(set)
available_items = available.items()
for wanted_const in wanted_consts:
cfgs = frozenset(
cfg for cfg, consts in available_items if wanted_const in consts
)
if not cfgs:
# We have no cfgs for a wanted const :/
continue
groups[cfgs].add(wanted_const)
# Step 4: Build output
output = ""
for cfgs, consts in sorted(groups.items(), key=lambda t: (len(t[0]), sorted(t[0]))):
target = next((target for target in TARGETS if target.cfgs == cfgs), None)
if target:
# If we found an exact target. Add its "extras" as-is
consts |= target.extras
cfgs_inner = ",".join(sorted(map(str, cfgs)))
if len(cfgs) >= 2:
cfgs_rust = f"#[cfg(any({cfgs_inner}))]"
else:
cfgs_rust = f"#[cfg({cfgs_inner})]"
imports = ",".join(consts)
entry = f"""
{cfgs_rust}
#[pyattr]
use libc::{{{imports}}};
""".strip()
output += f"{entry}\n\n"
print(rustfmt(output))
if __name__ == "__main__":
main()