From 46e5197b171e655825923fff094c88b6ce42aee3 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 9 Oct 2026 14:26:19 +0800 Subject: [PATCH 1/3] Fix generated Python package long-path installs Selectively shorten Python module paths with UTF-16, namespace, bytecode and atomic-write headroom. Compact layout-scoped setuptools build and wheel staging directories. Record the complete producer version and reject incompatible or unstamped generated output before mutation, preserving same-version incremental generation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2016e084-e482-4076-abde-eb8c13baf510 --- bindings/py/README.md | 5 + .../test_generated_python_long_paths.ps1 | 55 +++- .../python/verify_generated_python_install.py | 80 ++++++ tools/dynwinrt-codegen/README.md | 25 +- tools/dynwinrt-codegen/python/README.md | 48 +++- tools/dynwinrt-codegen/src/codegen/package.rs | 8 +- .../src/codegen/winrt/python/naming.rs | 253 +++++++++++++---- tools/dynwinrt-codegen/src/main.rs | 195 ++++++++++++- tools/dynwinrt-codegen/tests/common/mod.rs | 6 + .../tests/observable_map_test.rs | 61 ++-- .../tests/observable_vector_test.rs | 32 ++- .../tests/python_consumer_typing_test.rs | 53 ++-- .../tests/python_delegate_callback_test.rs | 34 ++- .../tests/python_generator_version_test.rs | 262 ++++++++++++++++++ .../tests/python_output_path_test.rs | 187 ++++++++++++- .../tests/python_stub_nullability_test.rs | 73 ++++- .../tests/snapshots/uri_py/__init__.py | 6 +- .../tests/snapshots/uri_pyi/__init__.pyi | 6 +- .../tests/winrt_implementation_test.rs | 22 +- 19 files changed, 1232 insertions(+), 179 deletions(-) create mode 100644 tools/dynwinrt-codegen/tests/python_generator_version_test.rs diff --git a/bindings/py/README.md b/bindings/py/README.md index c46f0934..c3a3bdac 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -18,6 +18,11 @@ Generated package manifests pin `dynwinrt` to the exact version of Do not mix generated bindings with an older runtime wheel. Upgrade to the matching runtime version and regenerate all Python bindings together; generated interface overloads fail explicitly when a required native guard is missing. +Generated Python packages record the full producer version separately. +Upgrades, downgrades, and legacy unstamped output require manually cleaning +the dedicated codegen output and regenerating the complete bindings selection; +incompatible generation fails without changing existing output. +See the [producer-version and path contracts](../../tools/dynwinrt-codegen/python/README.md#producer-version-and-regeneration). Generated `IReference` values are projected as `T | None`; native values, `None`, and generated `IReference_*` wrappers are accepted as inputs. diff --git a/eng/release/python/test_generated_python_long_paths.ps1 b/eng/release/python/test_generated_python_long_paths.ps1 index da10eee4..ab28883e 100644 --- a/eng/release/python/test_generated_python_long_paths.ps1 +++ b/eng/release/python/test_generated_python_long_paths.ps1 @@ -20,7 +20,8 @@ if ($root.Length -ne 104) { } $source = Join-Path $root "source\generated_bindings" $wheelDirectory = Join-Path $root "wheels" -$install = Join-Path $root "installed" +$sourceInstall = Join-Path $root "from-source" +$install = Join-Path $root ("i" * (135 - $root.Length - 1)) try { Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue @@ -33,9 +34,17 @@ try { if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $modules = Get-ChildItem -LiteralPath $source -File -Filter *.py - $tooLong = $modules | Where-Object { $_.BaseName.Length -gt 120 } + $tooLong = $modules | Where-Object { $_.BaseName.Length -gt 56 } if ($tooLong) { - throw "Generated Python module exceeds 120 characters: $($tooLong[0].Name)" + throw "Generated Python module exceeds 56 UTF-16 code units: $($tooLong[0].Name)" + } + $tooLong = Get-ChildItem -LiteralPath $source -File -Recurse | + Where-Object { + $_.Extension -in @(".py", ".pyi") -and + $_.FullName.Substring($source.Length + 1).Length -gt 60 + } + if ($tooLong) { + throw "Generated Python relative source path exceeds 60 UTF-16 code units: $($tooLong[0].Name)" } if (-not ($modules | Where-Object { $_.BaseName -match "_[0-9a-f]{16}$" })) { throw "Long-path fixture did not generate a hashed Python module" @@ -154,6 +163,15 @@ try { throw "Output package rename deleted the old build cache" } + & $Python -m pip install $source --no-deps --target $sourceInstall + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") ` + --source $source ` + --install $sourceInstall ` + --package renamed_bindings ` + --check-uri + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $Python -m pip wheel $source --no-deps --wheel-dir $wheelDirectory if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $wheel = Get-ChildItem -LiteralPath $wheelDirectory -Filter *.whl -File | @@ -165,11 +183,40 @@ try { & $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") ` --source $source ` --install $install ` - --package renamed_bindings + --package renamed_bindings ` + --check-uri if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $Python -m compileall -q -o 0 -o 1 -o 2 (Join-Path $install "renamed_bindings") + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $tooLong = Get-ChildItem -LiteralPath (Join-Path $install "renamed_bindings") -File -Recurse | + Where-Object { $_.FullName.Length -gt 259 } + if ($tooLong) { + throw "Installed Python source/stub/cache exceeds 259 UTF-16 code units: $($tooLong[0].FullName)" + } if (Test-Path -LiteralPath (Join-Path $install "generated_bindings")) { throw "Renamed wheel retained the old generated_bindings package" } + + $untypedSource = Join-Path $root "untyped_bindings" + $untypedWheels = Join-Path $root "untyped-wheels" + & $Codegen generate ` + --class-name Windows.Foundation.Uri,Windows.Devices.Enumeration.DeviceInformationCustomPairing ` + --lang py --no-pyi --output $untypedSource + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $Python -m pip wheel $untypedSource --no-deps --wheel-dir $untypedWheels + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $untypedWheel = Get-ChildItem -LiteralPath $untypedWheels -Filter *.whl -File | + Select-Object -First 1 + if (-not $untypedWheel) { throw "Untyped generated bindings wheel was not created" } + & $Python -m pip install $untypedWheel.FullName --no-deps --target $install + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") ` + --source $untypedSource --install $install --package untyped_bindings --check-uri + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ((Get-ChildItem (Join-Path $install "untyped_bindings") -Filter *.pyi -File -Recurse) -or + (Test-Path (Join-Path $install "untyped_bindings\py.typed"))) { + throw "Untyped wheel retained stubs or a py.typed marker" + } } finally { Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue } diff --git a/eng/release/python/verify_generated_python_install.py b/eng/release/python/verify_generated_python_install.py index 62c5d964..75e0205a 100644 --- a/eng/release/python/verify_generated_python_install.py +++ b/eng/release/python/verify_generated_python_install.py @@ -3,7 +3,11 @@ import argparse import importlib +import os +import subprocess import sys +import sysconfig +import tempfile from pathlib import Path @@ -40,11 +44,73 @@ def module_name(package: str, relative: Path) -> str: return ".".join((package, *parts)) +def check_uri_typing(package: str, install: Path, typed: bool) -> None: + environment = dict(os.environ) + environment.pop("MYPYPATH", None) + if install not in { + Path(sysconfig.get_path(name)).resolve() for name in ("purelib", "platlib") + }: + environment["MYPYPATH"] = str(install) + with tempfile.TemporaryDirectory(prefix="dtype-") as temporary: + directory = Path(temporary) + module = "windows.foundation" if typed else "windows__foundation__uri" + imports = f"from {package}.{module} import Uri\n" + result_type = "Uri" if typed else "Uri | None" + valid = ( + imports + + f"def consume(uri: Uri) -> {result_type}:\n" + + " host: str = uri.host\n" + + " return uri.combine_uri('sub/page')\n" + ) + if typed: + valid += ( + f"from {package}.windows.foundation.uri import Uri as PerTypeUri\n" + f"from {package}.windows__foundation__uri import Uri as FlatUri\n" + "uri: Uri = PerTypeUri('https://example.com')\n" + "other: Uri = FlatUri('https://example.com')\n" + ) + invalid = ( + imports + + f"def reject(uri: Uri) -> {result_type}:\n" + + " return uri.combine_uri(123)\n" + ) + for name, source in [("valid", valid), ("invalid", invalid)]: + consumer = directory / f"{name}.py" + consumer.write_text(source, encoding="utf-8") + command = [ + sys.executable, + "-m", + "mypy", + "--strict", + "--no-incremental", + "--no-pretty", + "--show-error-codes", + "--cache-dir", + str(directory / "m"), + str(consumer), + ] + if not typed: + command.extend(["--follow-untyped-imports", "--follow-imports=silent"]) + result = subprocess.run( + command, + capture_output=True, + text=True, + env=environment, + ) + errors = [line for line in result.stdout.splitlines() if ": error:" in line] + expected = 0 if name == "valid" else 1 + if result.returncode != expected or len(errors) != expected: + raise RuntimeError(result.stdout + result.stderr) + if name == "invalid" and not errors[0].endswith("[arg-type]"): + raise RuntimeError(result.stdout + result.stderr) + + def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--source", type=Path, required=True) parser.add_argument("--install", type=Path, required=True) parser.add_argument("--package", required=True) + parser.add_argument("--check-uri", action="store_true") args = parser.parse_args() source = args.source.resolve() @@ -71,6 +137,20 @@ def main() -> None: } for name in sorted(modules): importlib.import_module(name) + if args.check_uri: + from dynwinrt import RoApartment + + namespace = importlib.import_module(f"{args.package}.windows.foundation") + per_type = importlib.import_module(f"{args.package}.windows.foundation.uri") + flat = importlib.import_module(f"{args.package}.windows__foundation__uri") + assert namespace.Uri is per_type.Uri is flat.Uri + with RoApartment(): + uri = namespace.Uri("https://example.com/compact-paths") + assert uri.host == "example.com" + assert uri._obj.is_released() + check_uri_typing( + args.package, args.install.resolve(), (installed / "py.typed").exists() + ) print(f"verified {len(expected)} files and imported {len(modules)} modules") diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index f099ec2c..204d5dc5 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -175,9 +175,20 @@ layout, ownership, or cleanup information. See the The output directory belongs to codegen; do not store handwritten files in it. After changing metadata files, SDK versions, or reference inputs, regenerate the -complete output. Python module components longer than 120 characters are -shortened with a stable readable prefix and hash suffix while public type names -remain unchanged. +complete output. Python module stems are selectively shortened to a 56-unit +UTF-16 relative-path budget, including namespace directories for public facades. +Public type names, namespace exports, and ordinary short module imports remain +unchanged; direct imports of shortened long modules must migrate. Compact, +layout-scoped setuptools build and wheel staging paths leave additional room +for source installation and bytecode caches. + +Python output records the complete producer `generator_version` in +`.dynwinrt-generator.json`. A different version, an unstamped generated package, +or corrupt producer metadata fails before changing existing output: manually +clean the dedicated output and regenerate the entire selection, or use fresh +output. Equal versions retain incremental behavior. This includes preview +versions and downgrades, but cannot detect unversioned same-version development +changes. See the [regeneration contract](python/README.md#producer-version-and-regeneration). That component budget does not constrain an arbitrary output root. On Windows, Python generation warns once about final `.py`/`.pyi` paths of 260 or more @@ -190,12 +201,8 @@ their owning interfaces through incremental renames. Python's package-level root exports drop an interface and its helpers when its short name becomes ambiguous, while namespace imports remain available. Python's heterogeneous interface-pair union is generated from validated inventory -records, not inferred from `.pyi` text. The first typed incremental generation -over an older inventory needs the original WinMD/`--ref` inputs for interfaces -whose implementation records are missing. If those inputs are unavailable, -generation fails atomically and leaves the previous output usable: supply the -listed metadata and retry, or fully regenerate the package. New inventories -retain these records, and `--no-pyi` does not require this typing migration. +records, not inferred from `.pyi` text. New inventories retain these records; +older producer versions require full regeneration as described above. After `--no-pyi`, include the earlier types when regenerating with stubs enabled (or fully regenerate the package). A typed append fails rather than publishing imports of missing retained declarations or dropping interfaces from the union. diff --git a/tools/dynwinrt-codegen/python/README.md b/tools/dynwinrt-codegen/python/README.md index e6793835..71140c34 100644 --- a/tools/dynwinrt-codegen/python/README.md +++ b/tools/dynwinrt-codegen/python/README.md @@ -180,6 +180,28 @@ complete output. Regenerate with the updated generator to pick up these consumer typing contracts, and use the matching runtime package and its stubs. No runtime API change or consumer cast is required. +### Producer version and regeneration + +`.dynwinrt-generator.json` records `generator_version`, the complete generator +package version, including any prerelease/preview suffix. This is a producer +stamp, not the generated distribution version, runtime dependency version, or +the type inventory's `schema_version`. + +New/empty output and non-generated user content need no stamp. Existing generated +output must have a valid stamp matching the running generator exactly. +Same-version generation retains the existing incremental behavior. +A different version (including a downgrade), missing stamp on generated +artifacts, or corrupt stamp causes an unsuccessful exit **before existing output +is changed**, also in `--dry-run`. Manually clean the dedicated output directory +and regenerate the **entire bindings selection**, or use a fresh output directory; +do not remove or edit only the stamp. The generator never automatically deletes +or migrates incompatible output. + +Every generator upgrade therefore requires full regeneration, followed by +rebuilding/reinstalling the affected packages with the matching runtime. +Unversioned development changes with the same package version are not detected +by this check; use fresh output for those changes too. + ### Closed-generic stub migration Python stubs now identify closed generic interfaces by their complete semantic @@ -212,11 +234,26 @@ closed identity, even when their local projection names differ. - Some APIs require their Windows component, package identity, or framework bootstrap to be present at runtime. -Python module components longer than 120 characters are shortened with a stable -readable prefix and hash suffix while public type names remain unchanged. +Python implementation module stems use a 56 UTF-16-code-unit budget. Public +per-type module stems use the remaining budget after their namespace directories. +Only over-budget names are shortened with a readable prefix and stable hash of +the complete type identity. Public type names, namespace exports, and ordinary +short per-type and flat-module imports remain unchanged. Direct imports of +shortened long modules must migrate; no unsafe long-filename shims are emitted. ### Windows path length +The relative stem budget allows up to 60 UTF-16 code units for `.pyi` source paths +and reserves space for optimized CPython 3.11–3.14 `__pycache__` filenames and +their atomic-write temporary suffixes. For example, it fits the legacy 259-unit +limit with a 130-unit site-packages prefix and a 16-unit package name, including +a maximum-width 64-bit temporary identifier. Deep metadata namespaces may exceed this +budget even with a minimal basename; their namespace hierarchy is not flattened. +Generated `setup.cfg` also shortens the isolated setuptools build cache to +`.b/` and wheel staging to `.b//w`, avoiding +the extra default `bdist./wheel` nesting. Cache isolation still tracks +the source layout and import package name. + A short module name does not guarantee a short **absolute** path. In deep checkouts, codegen can successfully write files that ordinary Python imports, mypy, or pip cannot open. CPython supports long paths on appropriately @@ -234,9 +271,10 @@ shorter the output root needs to be. Relative `--output` paths are resolved from the current directory; temporary transactional staging paths are not counted. `--dry-run` checks the requested projection's planned source paths, aggregating all selected namespaces into one warning; `--no-pyi` excludes -stubs. This is a **compatibility risk diagnostic**: -generation still succeeds, and module names, imports, layout, and bytes are -unchanged. +stubs. This remains a **compatibility risk diagnostic**: generation still +succeeds without a further root-dependent naming change. The deterministic +module budget and compact staging do not guarantee arbitrary checkout, +package-name, build-temporary-directory, or venv depths. Prefer a shorter checkout such as `C:\src\dynwinrt`, or generate directly into a short root and run consumers there: diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index bed4130c..fee77bfe 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -96,7 +96,10 @@ pub fn render_python_setup_cfg(build_cache_key: &str) -> String { format!( "# Generated by dynwinrt-codegen — do not edit\n\ [build]\n\ - build-base = .dynwinrt-build/{build_cache_key}\n" + build-base = .b/{build_cache_key}\n\ + \n\ + [bdist_wheel]\n\ + bdist-dir = .b/{build_cache_key}/w\n" ) } @@ -362,6 +365,7 @@ mod tests { fn python_build_cache_is_layout_scoped() { let out = render_python_setup_cfg("0123456789abcdef"); - assert!(out.contains("build-base = .dynwinrt-build/0123456789abcdef")); + assert!(out.contains("build-base = .b/0123456789abcdef")); + assert!(out.contains("[bdist_wheel]\nbdist-dir = .b/0123456789abcdef/w")); } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index 54a5f69b..56bf3bc0 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -153,8 +153,13 @@ struct PythonProjection { reference_name: String, } -const MAX_PYTHON_MODULE_COMPONENT_LENGTH: usize = 120; +// Reserve __pycache__ (12), the optimized CPython 3.11-3.14 suffix (22), and +// _write_atomic's "." + a 64-bit decimal id (21). A 130-unit site-packages root, +// 16-unit package name and two separators then fit within 259 UTF-16 units. +const PYTHON_MODULE_PATH_BUDGET: usize = 56; +const MAX_PYTHON_NAMESPACE_COMPONENT_LENGTH: usize = 120; const MODULE_HASH_HEX_LENGTH: usize = 16; +const MIN_HASHED_MODULE_BUDGET: usize = 19; // _t_ + hash fn stable_module_hash(value: &str) -> u64 { let mut hash = 0xcbf29ce484222325_u64; @@ -165,22 +170,32 @@ fn stable_module_hash(value: &str) -> u64 { hash } -fn shorten_module_component_with_hash_input(value: &str, hash_input: &str) -> String { - if value.chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH { +fn shorten_module_component_with_hash_input( + value: &str, + hash_input: &str, + budget: usize, +) -> String { + let budget = budget.max(MIN_HASHED_MODULE_BUDGET); + if value.encode_utf16().count() <= budget { return value.to_string(); } - let prefix_length = MAX_PYTHON_MODULE_COMPONENT_LENGTH - MODULE_HASH_HEX_LENGTH - 1; + let prefix_length = budget - MODULE_HASH_HEX_LENGTH - 1; + let mut length = 0; let prefix = value .chars() - .take(prefix_length) + .take_while(|character| { + length += character.len_utf16(); + length <= prefix_length + }) .collect::() .trim_end_matches('_') .to_string(); + let prefix = if prefix.is_empty() { "_t" } else { &prefix }; format!("{prefix}_{:016x}", stable_module_hash(hash_input)) } fn shorten_module_component(value: &str) -> String { - shorten_module_component_with_hash_input(value, value) + shorten_module_component_with_hash_input(value, value, PYTHON_MODULE_PATH_BUDGET) } fn identity_kind_name(kind: TypeIdentityKind) -> &'static str { @@ -503,28 +518,43 @@ fn qualified_module_name( } else { format!("{namespace}__{}", to_snake_case(projected_name)) }; - shorten_module_component_with_hash_input(&candidate, &identity.canonical_key()) + shorten_module_component_with_hash_input( + &candidate, + &identity.canonical_key(), + PYTHON_MODULE_PATH_BUDGET, + ) +} + +fn unqualified_module_name(identity: &PythonTypeIdentity, projected_name: &str) -> String { + shorten_module_component_with_hash_input( + &to_snake_case(projected_name), + &identity.canonical_key(), + PYTHON_MODULE_PATH_BUDGET, + ) } fn public_module_name(identity: &PythonTypeIdentity, projected_name: &str) -> String { - let namespace = identity.namespace().unwrap_or_default(); - let qualified = qualified_module_name(identity, namespace, projected_name); - let prefix = python_namespace_segments(namespace).join("__"); - if prefix.is_empty() { - return qualified; - } - // Budget the namespace as well as the basename. Otherwise a readable flat - // module can have a facade path that Windows Python cannot open. - qualified - .strip_prefix(&format!("{prefix}__")) - .filter(|name| !name.is_empty()) - .map(str::to_string) - .unwrap_or_else(|| { - format!( - "type_{:016x}", - stable_module_hash(&identity.canonical_key()) - ) - }) + public_module_name_with_hash_input( + identity.namespace().unwrap_or_default(), + projected_name, + &identity.canonical_key(), + ) +} + +fn public_module_name_with_hash_input( + namespace: &str, + projected_name: &str, + hash_input: &str, +) -> String { + let namespace = python_namespace_segments(namespace).join("\\"); + let namespace_length = namespace.encode_utf16().count() + usize::from(!namespace.is_empty()); + // Very deep metadata namespaces can exceed the budget even with a minimal + // basename. Keep their hierarchy intact; the final-path diagnostic still applies. + shorten_module_component_with_hash_input( + &to_snake_case(projected_name), + hash_input, + PYTHON_MODULE_PATH_BUDGET.saturating_sub(namespace_length), + ) } /// Explicit, immutable naming and lookup state for one Python projection. @@ -615,7 +645,7 @@ impl PythonProjectionContext { ) { qualified_module_name(&identity, namespace, &projected_name) } else { - public_module.clone() + unqualified_module_name(&identity, &projected_name) }; if let Some(existing) = @@ -1358,7 +1388,7 @@ impl PythonProjectionContext { &projected_name, ) } else { - public_module_name(&identity, &projected_name) + unqualified_module_name(&identity, &projected_name) } }) } @@ -1424,7 +1454,14 @@ pub fn python_namespace_segments(namespace: &str) -> Vec { namespace .split('.') .filter(|segment| !segment.is_empty()) - .map(|segment| shorten_module_component(&to_snake_case(segment))) + .map(|segment| { + let name = to_snake_case(segment); + shorten_module_component_with_hash_input( + &name, + &name, + MAX_PYTHON_NAMESPACE_COMPONENT_LENGTH, + ) + }) .collect() } @@ -1434,7 +1471,11 @@ pub fn python_public_module_name(name: &str) -> String { pub fn python_public_qualified_module_name(namespace: &str, name: &str) -> String { let mut segments = python_namespace_segments(namespace); - segments.push(python_public_module_name(name)); + segments.push(public_module_name_with_hash_input( + namespace, + name, + &format!("{namespace}.{name}"), + )); segments.join(".") } @@ -1998,13 +2039,10 @@ mod tests { let name = "TypedEventHandler_MediaPlaybackCommandManager_MediaPlaybackCommandManagerAutoRepeatModeReceivedEventArgsAdditionalCompatibilitySuffix"; let other = format!("{name}2"); let shortened = python_public_module_name(name); - assert_eq!( - shortened.chars().count(), - MAX_PYTHON_MODULE_COMPONENT_LENGTH - ); + assert_eq!(shortened.encode_utf16().count(), PYTHON_MODULE_PATH_BUDGET); assert_eq!(shortened, python_public_module_name(name)); assert_ne!(shortened, python_public_module_name(&other)); - assert!(shortened.starts_with("typed_event_handler_media_playback_command_manager")); + assert!(shortened.starts_with("typed_event_handler_media_playback")); } #[test] @@ -2013,20 +2051,18 @@ mod tests { let identity = TypeIdentity::named(TypeIdentityKind::Delegate, "Windows.Foundation", name); let context = PythonProjectionContext::packaged([identity.clone()]).unwrap(); let implementation = context.implementation_module(&identity); - assert!(implementation.chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH); + assert!(implementation.encode_utf16().count() <= PYTHON_MODULE_PATH_BUDGET); assert_eq!(implementation, context.implementation_module(&identity)); assert!( - context.public_module(&identity).chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH + context + .public_qualified_module(&identity) + .encode_utf16() + .count() + <= PYTHON_MODULE_PATH_BUDGET ); assert_eq!( - context.public_module(&identity), - implementation - .strip_prefix("windows__foundation__") - .unwrap() - ); - assert!( - context.public_qualified_module(&identity).chars().count() - <= MAX_PYTHON_MODULE_COMPONENT_LENGTH + context.public_module(&identity).rsplit('_').next(), + implementation.rsplit('_').next(), ); } @@ -2056,16 +2092,15 @@ mod tests { .unwrap(); let implementation = context.implementation_module(&identity); let public = context.public_module(&identity); - assert_eq!( - public, - implementation - .strip_prefix("windows__foundation__") - .unwrap() - ); + assert_eq!(public.rsplit('_').next(), implementation.rsplit('_').next(),); assert!( - context.public_qualified_module(&identity).len() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH + context + .public_qualified_module(&identity) + .encode_utf16() + .count() + <= PYTHON_MODULE_PATH_BUDGET ); - assert!(public.starts_with("typed_event_handler_background_task_registration_group")); + assert!(public.starts_with("typed_event_handler")); assert_eq!(public, context.public_module(&identity)); assert_ne!( public, @@ -2085,6 +2120,109 @@ mod tests { ); } + #[test] + fn module_budgets_count_utf16_without_splitting_characters() { + let unicode = "\u{10428}".repeat(40); + assert_eq!(unicode.chars().count(), 40); + assert_eq!(unicode.encode_utf16().count(), 80); + let shortened = python_public_module_name(&unicode); + assert!(shortened.encode_utf16().count() <= PYTHON_MODULE_PATH_BUDGET); + assert!(shortened.starts_with("\u{10428}")); + assert!(shortened.ends_with(&format!("{:016x}", stable_module_hash(&unicode)))); + + let namespace = "\u{10428}".repeat(70); + let segments = python_namespace_segments(&namespace); + assert_eq!(segments.len(), 1); + assert!(segments[0].encode_utf16().count() <= MAX_PYTHON_NAMESPACE_COMPONENT_LENGTH); + } + + #[test] + fn module_budget_reserves_the_complete_atomic_bytecode_path() { + let site_packages = format!(r"C:\{}", "x".repeat(127)); + let package = "p".repeat(16); + let module = "m".repeat(PYTHON_MODULE_PATH_BUDGET); + let temporary = format!( + r"{site_packages}\{package}\__pycache__\{module}.cpython-314.opt-2.pyc.{}", + u64::MAX, + ); + assert_eq!(site_packages.encode_utf16().count(), 130); + assert_eq!(temporary.encode_utf16().count(), 259); + } + + #[test] + fn only_over_budget_modules_change_and_public_paths_include_namespaces() { + let short = TypeIdentity::named(TypeIdentityKind::Class, "Windows.Foundation", "Uri"); + let long = TypeIdentity::named( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "I".repeat(PYTHON_MODULE_PATH_BUDGET), + ); + let context = PythonProjectionContext::packaged([short.clone(), long.clone()]).unwrap(); + assert_eq!( + context.implementation_module(&short), + "windows__foundation__uri" + ); + assert_eq!( + context.public_qualified_module(&short), + "windows.foundation.uri" + ); + assert_eq!( + context.projected_name(&long), + "I".repeat(PYTHON_MODULE_PATH_BUDGET) + ); + for module in [ + context.implementation_module(&long), + context.public_qualified_module(&long), + ] { + assert!(module.encode_utf16().count() <= PYTHON_MODULE_PATH_BUDGET); + } + assert_eq!( + python_public_module_name(&"x".repeat(PYTHON_MODULE_PATH_BUDGET)), + "x".repeat(PYTHON_MODULE_PATH_BUDGET), + ); + assert_ne!( + python_public_module_name(&"x".repeat(PYTHON_MODULE_PATH_BUDGET + 1)), + "x".repeat(PYTHON_MODULE_PATH_BUDGET + 1), + ); + } + + #[test] + fn shortened_modules_fail_on_collisions_with_readable_names() { + let identity = TypeIdentity::named(TypeIdentityKind::Class, "", "x".repeat(80)); + let context = PythonProjectionContext::packaged([identity.clone()]).unwrap(); + let collision = TypeIdentity::named( + TypeIdentityKind::Class, + "", + context.implementation_module(&identity), + ); + let error = PythonProjectionContext::packaged([identity, collision]).unwrap_err(); + assert!( + error.contains("Python implementation module collision"), + "{error}" + ); + } + + #[test] + fn standalone_generics_keep_short_module_names_without_a_facade_budget() { + let identity = TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IIterator", + [TypeIdentity::named( + TypeIdentityKind::Interface, + "Windows.Foundation", + "IWwwFormUrlDecoderEntry", + )], + ); + let context = PythonProjectionContext::new([identity.clone()], false).unwrap(); + for module in [ + context.implementation_module(&identity), + PythonProjectionContext::default().implementation_module(&identity), + ] { + assert_eq!(module, "i_iterator_i_www_form_url_decoder_entry"); + } + } + #[test] fn facade_shortening_keeps_a_valid_name_when_namespace_uses_the_budget() { let identity = TypeIdentity::named( @@ -2094,8 +2232,15 @@ mod tests { ); let context = PythonProjectionContext::packaged([identity.clone()]).unwrap(); let public = context.public_module(&identity); - assert!(public.starts_with("type_"), "{public}"); - assert_eq!(public.len(), 5 + MODULE_HASH_HEX_LENGTH); + assert_eq!(public, "i_value"); + let long = TypeIdentity::named( + TypeIdentityKind::Interface, + "VeryLongNamespace".repeat(12), + "IValue".repeat(20), + ); + let public = context.public_module(&long); + assert!(public.encode_utf16().count() <= MIN_HASHED_MODULE_BUDGET); + assert!(public.as_bytes()[0].is_ascii_alphabetic() || public.starts_with('_')); } #[test] diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index c0c3ae92..658045eb 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -516,10 +516,20 @@ fn run() -> Result<(), String> { } let mut output_transaction = if matches!(lang.as_str(), "js" | "py") && !dry_run && !output_contains_cwd { - Some(OutputTransaction::begin(final_output_dir)?) + Some(if lang == "py" { + OutputTransaction::begin_with_preflight( + final_output_dir, + validate_python_generator_version, + )? + } else { + OutputTransaction::begin(final_output_dir)? + }) } else { None }; + if lang == "py" && dry_run { + validate_python_generator_version(final_output_dir)?; + } let effective_output_dir = output_transaction .as_ref() .map(|transaction| transaction.stage_dir().to_path_buf()) @@ -1236,6 +1246,7 @@ fn run() -> Result<(), String> { if lang == "py" && !dry_run { write_python_package_manifest(output_dir, final_output_dir)?; + write_python_generator_metadata(output_dir)?; let files = write_python_generated_inventory(output_dir, pyi)?; python_output_paths::warn(final_output_dir, &files)?; } @@ -5763,6 +5774,7 @@ fn recover_interrupted_output_transaction( parent: &Path, leaf: &str, final_dir: &Path, + preflight: impl FnOnce(&Path) -> Result<(), String>, ) -> Result<(), String> { let stage_prefix = format!(".{leaf}.dynwinrt-stage-"); let backup_prefix = format!(".{leaf}.dynwinrt-backup-"); @@ -5794,7 +5806,7 @@ fn recover_interrupted_output_transaction( } } if residues.is_empty() { - return Ok(()); + return preflight(final_dir); } if residues.len() != 1 { return Err(format!( @@ -5815,6 +5827,11 @@ fn recover_interrupted_output_transaction( if final_owned { validate_transaction_owner(final_dir, &nonce)?; } + preflight(if final_exists { + final_dir + } else { + residue.backup.as_deref().unwrap_or(final_dir) + })?; match ( final_exists, @@ -5903,6 +5920,13 @@ impl OutputTransaction { const LOCK_TIMEOUT: Duration = Duration::from_secs(120); fn begin(requested_final_dir: &Path) -> Result { + Self::begin_with_preflight(requested_final_dir, |_| Ok(())) + } + + fn begin_with_preflight( + requested_final_dir: &Path, + preflight: impl FnOnce(&Path) -> Result<(), String>, + ) -> Result { let absolute = if requested_final_dir.is_absolute() { requested_final_dir.to_path_buf() } else { @@ -6004,7 +6028,7 @@ impl OutputTransaction { std::thread::sleep(Duration::from_millis(delay)); } - recover_interrupted_output_transaction(parent, leaf, &final_dir)?; + recover_interrupted_output_transaction(parent, leaf, &final_dir, preflight)?; ensure_no_orphaned_transaction_artifacts(parent, leaf)?; let nonce = transaction_nonce(&final_dir); let stage_dir = parent.join(format!(".{leaf}.dynwinrt-stage-{nonce}")); @@ -6788,6 +6812,105 @@ fn python_build_cache_key(output_dir: &Path, import_name: &str) -> Result String { + format!( + "{reason} in '{}'. Manually clean the dedicated codegen output directory \ + and regenerate the entire bindings selection with dynwinrt-codegen {}. \ + Existing output has not been changed.", + output_dir.display(), + env!("CARGO_PKG_VERSION"), + ) +} + +fn validate_python_generator_version(output_dir: &Path) -> Result<(), String> { + validate_python_generator_version_against(output_dir, env!("CARGO_PKG_VERSION")) +} + +fn validate_python_generator_version_against( + output_dir: &Path, + generator_version: &str, +) -> Result<(), String> { + let metadata = match fs::symlink_metadata(output_dir) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => { + return Err(format!( + "Failed to inspect {}: {error}", + output_dir.display() + )); + } + }; + if is_link_or_reparse_point(&metadata) || !metadata.is_dir() { + return Err(format!( + "Python generated output '{}' must be a non-linked directory", + output_dir.display() + )); + } + let path = output_dir.join(PYTHON_GENERATOR_METADATA); + match fs::symlink_metadata(&path) { + Ok(metadata) => { + if is_link_or_reparse_point(&metadata) || !metadata.is_file() { + return Err(python_regeneration_error( + output_dir, + "Invalid Python generator metadata", + )); + } + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + let metadata: PythonGeneratorMetadata = + serde_json::from_str(&content).map_err(|error| { + python_regeneration_error( + output_dir, + &format!("Invalid Python generator metadata: {error}"), + ) + })?; + if metadata.generator_version != generator_version { + return Err(python_regeneration_error( + output_dir, + &format!( + "Python generator_version {:?} does not match current producer {:?}", + metadata.generator_version, generator_version, + ), + )); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if path_entry_exists(&output_dir.join(PYTHON_GENERATED_INVENTORY)) + || path_entry_exists(&output_dir.join(PYTHON_TYPE_INVENTORY)) + || !collect_generated_python_files(output_dir, false, false)?.is_empty() + { + return Err(python_regeneration_error( + output_dir, + "Existing generated Python artifacts have no recorded generator_version", + )); + } + } + Err(error) => { + return Err(format!("Failed to inspect {}: {error}", path.display())); + } + } + Ok(()) +} + +fn write_python_generator_metadata(output_dir: &Path) -> Result<(), String> { + let metadata = PythonGeneratorMetadata { + generator_version: env!("CARGO_PKG_VERSION").into(), + }; + let content = serde_json::to_string_pretty(&metadata) + .map_err(|error| format!("Failed to serialize Python generator metadata: {error}"))?; + write_file( + &output_dir.join(PYTHON_GENERATOR_METADATA), + &format!("{content}\n"), + ) +} fn python_inventory_contains(output_dir: &Path, relative_path: &Path) -> Result { let inventory_path = output_dir.join(PYTHON_GENERATED_INVENTORY); @@ -6991,6 +7114,7 @@ fn collect_generated_python_files( let generated = match entry.file_name().to_str() { Some("py.typed") => include_root_marker && current == root, Some("pyproject.toml" | "setup.cfg") => include_root_manifest && current == root, + Some(PYTHON_GENERATOR_METADATA) => include_root_manifest && current == root, Some(name) if name.ends_with(".py") || name.ends_with(".pyi") => { fs::read_to_string(&path) .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))? @@ -7052,7 +7176,7 @@ fn is_generator_owned_python_source_file( && relative.file_name().is_some_and(|name| { matches!( name.to_str(), - Some("pyproject.toml" | "setup.cfg" | "py.typed") + Some("pyproject.toml" | "setup.cfg" | "py.typed" | PYTHON_GENERATOR_METADATA) ) }) { @@ -10679,7 +10803,7 @@ mod tests { assert_eq!( context.implementation_module(&existing[0]), - "windows__foundation__collections__i_iterable_i_key_value_pair_object_object" + "windows__foundation__collections__i_ite_a890e3f1d2aa4c5f" ); } @@ -10696,7 +10820,7 @@ mod tests { let context = python_generation_context("", &[], &[], &[], &shared, &[]).unwrap(); assert_eq!( context.implementation_module_for_interface(&shared[0]), - "windows__foundation__collections__i_iterable_i_key_value_pair_object_object" + "windows__foundation__collections__i_ite_a890e3f1d2aa4c5f" ); write_python_type_inventory(&output, &[]).unwrap(); @@ -10776,7 +10900,7 @@ mod tests { assert!( fs::read_to_string(output.join("setup.cfg")) .unwrap() - .contains(&format!("build-base = .dynwinrt-build/{initial}")) + .contains(&format!("build-base = .b/{initial}")) ); let inventory = fs::read_to_string(output.join(PYTHON_GENERATED_INVENTORY)).unwrap(); assert!(inventory.lines().any(|line| line == "setup.cfg")); @@ -10784,6 +10908,63 @@ mod tests { fs::remove_dir_all(output).unwrap(); } + #[test] + fn python_producer_version_compares_complete_preview_versions() { + let output = test_directory("python-preview-producer"); + fs::create_dir_all(&output).unwrap(); + let preview = "0.1.0-preview.21"; + fs::write( + output.join(PYTHON_GENERATOR_METADATA), + format!(r#"{{"generator_version":"{preview}"}}"#), + ) + .unwrap(); + validate_python_generator_version_against(&output, preview).unwrap(); + for other in ["0.1.0", "0.1.0-preview.20", "0.1.0-preview.22"] { + let error = validate_python_generator_version_against(&output, other).unwrap_err(); + assert!(error.contains(preview), "{error}"); + assert!(error.contains(other), "{error}"); + assert!( + error.contains("regenerate the entire bindings selection"), + "{error}" + ); + } + fs::remove_dir_all(output).unwrap(); + } + + #[test] + fn python_producer_preflight_preserves_incompatible_interrupted_output() { + let output = test_directory("python-incompatible-interrupted"); + let leaf = output.file_name().unwrap().to_str().unwrap(); + let parent = output.parent().unwrap(); + let nonce = "incompatible-producer"; + let backup = parent.join(format!(".{leaf}.dynwinrt-backup-{nonce}")); + let stage = parent.join(format!(".{leaf}.dynwinrt-stage-{nonce}")); + for directory in [&backup, &stage] { + fs::create_dir_all(directory).unwrap(); + write_transaction_owner(directory, nonce).unwrap(); + } + fs::write( + backup.join(PYTHON_GENERATOR_METADATA), + r#"{"generator_version":"0.0.1"}"#, + ) + .unwrap(); + fs::write(backup.join("old.py"), GENERATED_PYTHON_HEADER).unwrap(); + let error = match OutputTransaction::begin_with_preflight( + &output, + validate_python_generator_version, + ) { + Ok(_) => panic!("incompatible backup must not be restored or changed"), + Err(error) => error, + }; + assert!(error.contains("does not match current producer"), "{error}"); + assert!(!output.exists()); + assert!(backup.join("old.py").exists()); + validate_transaction_owner(&backup, nonce).unwrap(); + validate_transaction_owner(&stage, nonce).unwrap(); + remove_owned_transaction_dir(&backup, nonce).unwrap(); + remove_owned_transaction_dir(&stage, nonce).unwrap(); + } + #[test] fn stale_cleanup_removes_only_inventory_files() { let output = test_directory("stale-cleanup"); diff --git a/tools/dynwinrt-codegen/tests/common/mod.rs b/tools/dynwinrt-codegen/tests/common/mod.rs index 6e86b096..bfb298b8 100644 --- a/tools/dynwinrt-codegen/tests/common/mod.rs +++ b/tools/dynwinrt-codegen/tests/common/mod.rs @@ -9,6 +9,12 @@ use dynwinrt_codegen::meta::{ }; use dynwinrt_codegen::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; +pub fn python_module(identity: TypeIdentity) -> String { + PythonProjectionContext::packaged([identity.clone()]) + .unwrap() + .implementation_module(&identity) +} + /// Generated `on_`, `subscribe_` and `once_` signatures for an event. `on_` and /// `subscribe_` also accept native delegates. pub fn event_signatures(event: &str, _callback: &str) -> [String; 3] { diff --git a/tools/dynwinrt-codegen/tests/observable_map_test.rs b/tools/dynwinrt-codegen/tests/observable_map_test.rs index af04b3a4..546d91af 100644 --- a/tools/dynwinrt-codegen/tests/observable_map_test.rs +++ b/tools/dynwinrt-codegen/tests/observable_map_test.rs @@ -9,8 +9,9 @@ use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::atomic::{AtomicU64, Ordering}; +use dynwinrt_codegen::codegen::python::PythonProjectionContext; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; -use dynwinrt_codegen::types::TypeMeta; +use dynwinrt_codegen::types::{TypeIdentityKind, TypeMeta}; const COLLECTIONS: &str = "Windows.Foundation.Collections"; const WINDOWS_WINMD: &str = @@ -25,6 +26,11 @@ fn collections_type(name: &str, piid: &str, args: Vec) -> TypeMeta { } } +fn packaged_collection_module(name: &str, args: Vec) -> String { + let typ = collections_type(name, "", args); + common::python_module(typ.type_identity()) +} + fn map_changed_handler(key: TypeMeta, value: TypeMeta) -> TypeMeta { collections_type( "MapChangedEventHandler`2", @@ -454,10 +460,15 @@ fn runtime_class_vector_changed_events_import_observable_sender_and_arguments() ), "{py}" ); + let arguments_module = PythonProjectionContext::default().implementation_module_for_named( + TypeIdentityKind::Interface, + COLLECTIONS, + "IVectorChangedEventArgs", + ); assert!( - py.contains( - "_dynwinrt_symbol('windows__foundation__collections__i_vector_changed_event_args', 'IVectorChangedEventArgs')(value))(__p1__)" - ), + py.contains(&format!( + "_dynwinrt_symbol('{arguments_module}', 'IVectorChangedEventArgs')(value))(__p1__)" + )), "{py}" ); for imported in [ @@ -543,30 +554,36 @@ fn windows_observable_maps_type_and_project_map_changed_handlers() { let callback = format!( "Callable[['IObservableMap_String_{value}', 'IMapChangedEventArgs_String'], object]" ); - let observable_module = format!( - "windows__foundation__collections__i_observable_map_string_{}", - value.to_lowercase() + let value_type = if value == "Object" { + TypeMeta::Object + } else { + TypeMeta::String + }; + let observable_module = packaged_collection_module( + "IObservableMap`2", + vec![TypeMeta::String, value_type.clone()], ); + let map_module = + packaged_collection_module("IMap`2", vec![TypeMeta::String, value_type.clone()]); + let map_view_module = + packaged_collection_module("IMapView`2", vec![TypeMeta::String, value_type]); + let arguments_module = + packaged_collection_module("IMapChangedEventArgs`1", vec![TypeMeta::String]); let sender = format!( "(lambda value: None if value.is_null() else _dynwinrt_symbol('{observable_module}', 'IObservableMap_String_{value}')(value))(__p0__)" ); - let args = "(lambda value: None if value.is_null() else _dynwinrt_symbol('windows__foundation__collections__i_map_changed_event_args_string', 'IMapChangedEventArgs_String')(value))(__p1__)"; + let args = format!( + "(lambda value: None if value.is_null() else _dynwinrt_symbol('{arguments_module}', 'IMapChangedEventArgs_String')(value))(__p1__)" + ); let projection = format!("lambda __p0__, __p1__: ({sender}, {args})"); let class_py = output.read(&format!("windows__foundation__collections__{class}.py")); let interface_py = output.read(&format!("{observable_module}.py")); - let map_py = output.read(&format!( - "windows__foundation__collections__i_map_string_{}.py", - value.to_lowercase() - )); - let map_view_py = output.read(&format!( - "windows__foundation__collections__i_map_view_string_{}.py", - value.to_lowercase() - )); + let map_py = output.read(&format!("{map_module}.py")); + let map_view_py = output.read(&format!("{map_view_module}.py")); assert!( interface_py.contains(&format!( - "_dynwinrt_map_dispatch = (_dynwinrt_symbol('windows__foundation__collections__i_map_string_{}', 'IID_IMap_String_{value}'), '_obj')", - value.to_lowercase() + "_dynwinrt_map_dispatch = (_dynwinrt_symbol('{map_module}', 'IID_IMap_String_{value}'), '_obj')", )), "{interface_py}" ); @@ -607,8 +624,7 @@ fn windows_observable_maps_type_and_project_map_changed_handlers() { } assert!( interface_py.contains(&format!( - "class IObservableMap_String_{value}(_dynwinrt_symbol('windows__foundation__collections__i_map_string_{}', 'IMap_String_{value}')):", - value.to_lowercase() + "class IObservableMap_String_{value}(_dynwinrt_symbol('{map_module}', 'IMap_String_{value}')):", )), "{interface_py}" ); @@ -653,8 +669,9 @@ fn windows_observable_map_returns_emit_their_mutable_map_base() { else { return; }; - let observable = - output.read("windows__foundation__collections__i_observable_map_string_string.py"); + let observable_module = + packaged_collection_module("IObservableMap`2", vec![TypeMeta::String, TypeMeta::String]); + let observable = output.read(&format!("{observable_module}.py")); assert!( observable.contains( "class IObservableMap_String_String(_dynwinrt_symbol('windows__foundation__collections__i_map_string_string', 'IMap_String_String')):" diff --git a/tools/dynwinrt-codegen/tests/observable_vector_test.rs b/tools/dynwinrt-codegen/tests/observable_vector_test.rs index 157eac49..3bb9181f 100644 --- a/tools/dynwinrt-codegen/tests/observable_vector_test.rs +++ b/tools/dynwinrt-codegen/tests/observable_vector_test.rs @@ -139,16 +139,19 @@ fn observable_vector_projects_python_mutable_sequence_and_typed_events() { for signature in common::event_signatures("vector_changed", callback) { assert!(py.contains(&signature), "{signature}\n{py}"); } - assert!( - py.contains( - "lambda __p0__, __p1__: (\ - (lambda value: None if value.is_null() else \ - _dynwinrt_symbol('i_observable_vector_object', 'IObservableVector_Object')(value))(__p0__), \ - (lambda value: None if value.is_null() else \ - _dynwinrt_symbol('windows__foundation__collections__i_vector_changed_event_args', 'IVectorChangedEventArgs')(value))(__p1__))" - ), - "{py}" - ); + let arguments_module = dynwinrt_codegen::codegen::python::PythonProjectionContext::default() + .implementation_module_for_named( + dynwinrt_codegen::types::TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IVectorChangedEventArgs", + ); + assert!(py.contains(&format!( + "lambda __p0__, __p1__: (\ + (lambda value: None if value.is_null() else \ + _dynwinrt_symbol('i_observable_vector_object', 'IObservableVector_Object')(value))(__p0__), \ + (lambda value: None if value.is_null() else \ + _dynwinrt_symbol('{arguments_module}', 'IVectorChangedEventArgs')(value))(__p1__))" + )), "{py}"); assert!(py.contains("_dynwinrt_delegate(callback,")); assert!(py.contains("_IObservableVector_Object.method(6).invoke(self._observable_obj")); @@ -159,9 +162,12 @@ fn observable_vector_projects_python_mutable_sequence_and_typed_events() { ), "{pyi}" ); - assert!(pyi.contains( - "from .windows__foundation__collections__i_vector_changed_event_args import IID_IVectorChangedEventArgs, IVectorChangedEventArgs" - ), "{pyi}"); + assert!( + pyi.contains(&format!( + "from .{arguments_module} import IID_IVectorChangedEventArgs, IVectorChangedEventArgs" + )), + "{pyi}" + ); assert!(pyi.contains(&format!("{create_signature} ...")), "{pyi}"); assert!( pyi.contains("def __getitem__(self, index: int) -> DynWinRTValue | None: ..."), diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index de6270cb..8eda636e 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -461,6 +463,13 @@ fn strict_consumers_separate_instances_factories_and_native_object_inputs() { let fixture = Fixture::new(); generate_fixture(&fixture, "first"); generate_fixture(&fixture, "second"); + let resource = TypeIdentity::named(TypeIdentityKind::Class, "Contoso", "Resource"); + let resource_map_module = common::python_module(TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IMap`2", + [resource.clone(), resource], + )); typecheck( &fixture, &["first", "second"], @@ -601,11 +610,11 @@ def invalid_collections(resource: Resource, unrelated: Unrelated, typecheck( &fixture, &["first"], - r#"from typing import assert_type + &r#"from typing import assert_type from dynwinrt import DynWinRTValue from first.contoso__resource import Resource from first.windows__foundation__collections__i_map_object_object import IMap_Object_Object -from first.windows__foundation__collections__i_map_resource_resource import IMap_Resource_Resource +from first.__RESOURCE_MAP_MODULE__ import IMap_Resource_Resource def nullable_reference_keys( objects: IMap_Object_Object, resources: IMap_Resource_Resource @@ -616,16 +625,17 @@ def nullable_reference_keys( resources.update({None: None}) assert_type(resources.setdefault(None, None), Resource | None) assert_type(resources[None], Resource | None) -"#, +"# + .replace("__RESOURCE_MAP_MODULE__", &resource_map_module), &[], ); pyright_typecheck( &fixture, - r#"from typing import assert_type + &r#"from typing import assert_type from dynwinrt import DynWinRTValue from first.contoso__resource import Resource from first.windows__foundation__collections__i_map_object_object import IMap_Object_Object -from first.windows__foundation__collections__i_map_resource_resource import IMap_Resource_Resource +from first.__RESOURCE_MAP_MODULE__ import IMap_Resource_Resource def nullable_reference_keys( objects: IMap_Object_Object, resources: IMap_Resource_Resource @@ -636,7 +646,8 @@ def nullable_reference_keys( resources.update({None: None}) assert_type(resources.setdefault(None, None), Resource | None) assert_type(resources[None], Resource | None) -"#, +"# + .replace("__RESOURCE_MAP_MODULE__", &resource_map_module), 0, ); typecheck( @@ -1622,12 +1633,18 @@ fn mutable_collection_mutators_accept_none() { ) .unwrap(); assert!(object_map_stub.contains("MutableMapping[DynWinRTValue | None, DynWinRTValue | None]")); - let pair_stub = fs::read_to_string( - fixture - .0 - .join("sdk") - .join("windows__foundation__collections__i_key_value_pair_object_object.pyi"), - ) + let pair_stub = fs::read_to_string(fixture.0.join("sdk").join(format!( + "{}.pyi", + common::python_module(TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IKeyValuePair`2", + [ + TypeMeta::Object.type_identity(), + TypeMeta::Object.type_identity() + ], + )) + ))) .unwrap(); assert!(pair_stub.contains("def key(self) -> DynWinRTValue | None: ...")); assert!(pair_stub.contains("def value(self) -> DynWinRTValue | None: ...")); @@ -1636,7 +1653,7 @@ fn mutable_collection_mutators_accept_none() { typecheck( &fixture, &["sdk"], - r#"from typing import assert_type + &r#"from typing import assert_type from dynwinrt import DynWinRTValue from sdk.windows.data.json import IJsonValue, JsonObject, JsonValue from sdk.windows.foundation import IStringable, Uri @@ -1647,7 +1664,7 @@ from sdk.windows.foundation.collections import ( ) from sdk.windows.storage import StorageFolder from sdk.windows__foundation__collections__property_set import IMap_String_Object -from sdk.windows__foundation__collections__i_map_i_stringable_i_stringable import ( +from sdk.__STRINGABLE_MODULE__ import ( IMap_IStringable_IStringable, ) @@ -1681,7 +1698,8 @@ def reference_keys( def string_keys(values: IMap_String_String) -> None: values["key"] = "value" values.get("key") -"#, +"# + .replace("__STRINGABLE_MODULE__", &stringable_module), &[], ); @@ -1780,7 +1798,7 @@ from sdk.windows.foundation.collections import ( IVector_String, IVector_StorageFolder, ) -from sdk.windows__foundation__collections__i_map_i_stringable_i_stringable import ( +from sdk.__STRINGABLE_MODULE__ import ( IMap_IStringable_IStringable, ) from sdk.windows__data__json__json_object import IID_IJsonValue, IMap_String_IJsonValue @@ -1914,7 +1932,8 @@ with RoApartment(1), projected_lifetime_scope(): raise AssertionError(f"{expected!r} was not raised") print("nullable-collection-native-ok", flush=True) "# - .replace("__NESTED_MODULE__", &nested_module); + .replace("__NESTED_MODULE__", &nested_module) + .replace("__STRINGABLE_MODULE__", &stringable_module); fs::write(fixture.0.join("nullable_collections.py"), script).unwrap(); let output = Command::new(python()) .args(["-B", "nullable_collections.py"]) diff --git a/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs b/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs index ed4576e7..702dd532 100644 --- a/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs +++ b/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs @@ -13,7 +13,7 @@ use std::process::Command; use std::sync::atomic::{AtomicU64, Ordering}; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; -use dynwinrt_codegen::types::{FieldMeta, TypeMeta}; +use dynwinrt_codegen::types::{FieldMeta, TypeIdentity, TypeIdentityKind, TypeMeta}; use windows_metadata::{ MethodAttributes, MethodCallAttributes, MethodImplAttributes, ParamAttributes, Signature, Type, TypeAttributes, Value, writer, @@ -500,10 +500,14 @@ fn bespoke_event_delegates_are_typed_and_projected() { else { return; }; - let module = "windows__application_model__background__background_task_registration"; + let module = common::python_module(TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.ApplicationModel.Background", + "BackgroundTaskRegistration", + )); let callback = "Callable[['BackgroundTaskRegistration', 'BackgroundTaskCompletedEventArgs'], object]"; - let py = output.read(module, "py"); + let py = output.read(&module, "py"); assert!( py.contains( "def on_completed(self, callback: Callable[..., object] | DynWinRTValue | DynWinRtDelegate):" @@ -517,16 +521,20 @@ fn bespoke_event_delegates_are_typed_and_projected() { assert!( py.contains(&format!( "'BackgroundTaskCompletedEventHandler_PARAM_TYPES'), lambda __p0__, __p1__: ({}, {}))", - class_wrapper(module, "BackgroundTaskRegistration", "__p0__"), + class_wrapper(&module, "BackgroundTaskRegistration", "__p0__"), class_wrapper( - "windows__application_model__background__background_task_completed_event_args", + &common::python_module(TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.ApplicationModel.Background", + "BackgroundTaskCompletedEventArgs", + )), "BackgroundTaskCompletedEventArgs", "__p1__" ) )), "{py}" ); - let pyi = output.read(module, "pyi"); + let pyi = output.read(&module, "pyi"); assert!( pyi.contains(&format!( "def subscribe_completed(self, callback: {callback} | 'DynWinRTValue | DynWinRtDelegate') -> Callable[[], None]: ..." @@ -553,14 +561,14 @@ fn runtime_delegate_annotations_resolve_and_stubs_remain_precise() { let property_runtime = output .0 .join("windows__foundation__collections__property_set.py"); - let bespoke_runtime = output - .0 - .join("windows__application_model__background__background_task_registration.py"); + let bespoke_module = common::python_module(TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.ApplicationModel.Background", + "BackgroundTaskRegistration", + )); + let bespoke_runtime = output.0.join(format!("{bespoke_module}.py")); let property_stub = output.read("windows__foundation__collections__property_set", "pyi"); - let bespoke_stub = output.read( - "windows__application_model__background__background_task_registration", - "pyi", - ); + let bespoke_stub = output.read(&bespoke_module, "pyi"); assert!( property_stub.contains( "def on_map_changed(self, callback: Callable[['IObservableMap_String_Object', \ diff --git a/tools/dynwinrt-codegen/tests/python_generator_version_test.rs b/tools/dynwinrt-codegen/tests/python_generator_version_test.rs new file mode 100644 index 00000000..132e769f --- /dev/null +++ b/tools/dynwinrt-codegen/tests/python_generator_version_test.rs @@ -0,0 +1,262 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows_metadata::{FieldAttributes, Type, TypeAttributes, Value, writer}; + +const STAMP: &str = ".dynwinrt-generator.json"; +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + root: PathBuf, + metadata: PathBuf, + output: PathBuf, +} + +impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "dpg{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + fs::create_dir_all(&root).unwrap(); + let metadata = root.join("VersionGuard.winmd"); + let mut file = writer::File::new("PythonVersionGuard"); + let base = file.TypeRef("System", "Enum"); + file.TypeDef( + "Windows.VersionGuard", + "Options", + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + file.Field( + "value__", + &Type::I32, + FieldAttributes::Public | FieldAttributes::SpecialName | FieldAttributes::RTSpecialName, + ); + let member = file.Field( + "One", + &Type::named("Windows.VersionGuard", "Options"), + FieldAttributes::Public + | FieldAttributes::Static + | FieldAttributes::Literal + | FieldAttributes::HasDefault, + ); + file.Constant(writer::HasConstant::Field(member), &Value::I32(1)); + fs::write(&metadata, file.into_stream()).unwrap(); + let output = root.join("bindings"); + Self { + root, + metadata, + output, + } + } + + fn command(&self) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(&self.metadata) + .args([ + "--namespace", + "Windows.VersionGuard", + "--lang", + "py", + "--output", + ]) + .arg(&self.output) + .env_remove("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT"); + command + } + + fn generate(&self) { + let output = self.command().output().unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + } + + fn refused_unchanged(&self, command: &mut Command) -> String { + let before = files(&self.output); + let output: Output = command.output().unwrap(); + assert_eq!(output.status.code(), Some(1)); + let error = String::from_utf8_lossy(&output.stderr); + assert!( + error.contains("Manually clean the dedicated codegen output"), + "{error}" + ); + assert!( + error.contains("regenerate the entire bindings selection"), + "{error}" + ); + assert!( + error.contains("Existing output has not been changed"), + "{error}" + ); + assert_eq!(files(&self.output), before); + for entry in fs::read_dir(&self.root).unwrap() { + let name = entry.unwrap().file_name(); + let name = name.to_string_lossy(); + assert!(!name.contains(".dynwinrt-stage-"), "{name}"); + assert!(!name.contains(".dynwinrt-backup-"), "{name}"); + } + error.into_owned() + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.root).unwrap(); + } +} + +fn files(root: &Path) -> BTreeMap> { + fn visit(root: &Path, current: &Path, result: &mut BTreeMap>) { + for entry in fs::read_dir(current).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + visit(root, &path, result); + } else { + result.insert( + path.strip_prefix(root).unwrap().into(), + fs::read(path).unwrap(), + ); + } + } + } + let mut result = BTreeMap::new(); + if root.is_dir() { + visit(root, root, &mut result); + } + result +} + +#[test] +fn new_and_non_generated_output_stamp_the_current_producer() { + for existing in ["new", "empty", "user"] { + let fixture = Fixture::new(); + if existing != "new" { + fs::create_dir(&fixture.output).unwrap(); + } + if existing == "user" { + fs::write(fixture.output.join("manual.py"), "VALUE = 42\n").unwrap(); + fs::write(fixture.output.join("manual.pyi"), "VALUE: int\n").unwrap(); + } + fixture.generate(); + let stamp: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join(STAMP)).unwrap()).unwrap(); + assert_eq!(stamp["generator_version"], env!("CARGO_PKG_VERSION")); + assert_eq!(stamp.as_object().unwrap().len(), 1); + let inventory = + fs::read_to_string(fixture.output.join(".dynwinrt-generated-files")).unwrap(); + assert!(inventory.lines().any(|line| line == STAMP)); + if existing == "user" { + assert_eq!( + fs::read_to_string(fixture.output.join("manual.py")).unwrap(), + "VALUE = 42\n" + ); + } + let before = files(&fixture.output); + fixture.generate(); + assert_eq!(files(&fixture.output), before); + } +} + +#[test] +fn changed_preview_upgrade_and_downgrade_producers_refuse_before_writes() { + let fixture = Fixture::new(); + fixture.generate(); + for version in ["0.0.1", "99.0.0", "0.1.0-preview.21"] { + fs::write( + fixture.output.join(STAMP), + format!(r#"{{"generator_version":"{version}"}}"#), + ) + .unwrap(); + for dry_run in [false, true] { + let mut command = fixture.command(); + if dry_run { + command.arg("--dry-run"); + } + let error = fixture.refused_unchanged(&mut command); + assert!(error.contains(version), "{error}"); + assert!(error.contains(env!("CARGO_PKG_VERSION")), "{error}"); + } + } +} + +#[test] +fn legacy_output_with_or_without_inventories_requires_full_regeneration() { + for artifacts in [ + vec![".dynwinrt-generated-files"], + vec![".dynwinrt-generated-types"], + vec!["old.py"], + vec!["old.pyi"], + vec!["windows\\__init__.py", "windows\\old.py"], + ] { + let fixture = Fixture::new(); + fs::create_dir(&fixture.output).unwrap(); + for artifact in artifacts { + let path = fixture.output.join(artifact); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write( + path, + "# Generated by dynwinrt-codegen \u{2014} do not edit\n", + ) + .unwrap(); + } + let error = fixture.refused_unchanged(&mut fixture.command()); + assert!(error.contains("no recorded generator_version"), "{error}"); + } +} + +#[test] +fn missing_and_corrupt_producer_metadata_preserve_all_existing_output() { + let fixture = Fixture::new(); + fixture.generate(); + fs::remove_file(fixture.output.join(STAMP)).unwrap(); + fixture.refused_unchanged(&mut fixture.command()); + for stamp in [ + "", + "{", + "{}", + r#"{"generator_version":null}"#, + r#"{"generator_version":1}"#, + r#"{"generator_version":""}"#, + r#"{"generator_version":"0.1.0","schema_version":2}"#, + r#"{"generator_version":"0.1.0","generator_version":"0.1.0"}"#, + ] { + fs::write(fixture.output.join(STAMP), stamp).unwrap(); + fixture.refused_unchanged(&mut fixture.command()); + } + fs::remove_file(fixture.output.join(STAMP)).unwrap(); + fs::create_dir(fixture.output.join(STAMP)).unwrap(); + fixture.refused_unchanged(&mut fixture.command()); +} + +#[test] +fn failed_publication_does_not_stamp_or_modify_the_old_output() { + let fixture = Fixture::new(); + fs::create_dir(&fixture.output).unwrap(); + fs::write(fixture.output.join("manual.py"), "VALUE = 42\n").unwrap(); + let before = files(&fixture.output); + let output = fixture + .command() + .env("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT", "before_publish") + .output() + .unwrap(); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Injected output transaction failure") + ); + assert_eq!(files(&fixture.output), before); + assert!(!fixture.output.join(STAMP).exists()); +} diff --git a/tools/dynwinrt-codegen/tests/python_output_path_test.rs b/tools/dynwinrt-codegen/tests/python_output_path_test.rs index d62eff3c..741f9f14 100644 --- a/tools/dynwinrt-codegen/tests/python_output_path_test.rs +++ b/tools/dynwinrt-codegen/tests/python_output_path_test.rs @@ -179,8 +179,8 @@ fn python_path_diagnostic_uses_actual_final_files_not_transactional_paths() { return; } let fixture = Fixture::new(); - let deep = fixture.output("deep", 137); - let shallow = fixture.output("short", 130); + let deep = fixture.output("deep", 201); + let shallow = fixture.output("short", 194); let output = device_command(&deep).output().unwrap(); successful(&output); let generated = files(&deep); @@ -220,7 +220,7 @@ fn python_path_diagnostic_uses_actual_final_files_not_transactional_paths() { "the no-warning control must exercise over-budget staging paths" ); - let unpublished = fixture.output("failure", 137); + let unpublished = fixture.output("failure", 201); let failure = device_command(&unpublished) .env("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT", "before_publish") .output() @@ -242,7 +242,7 @@ fn python_path_diagnostic_respects_relative_dry_run_and_no_pyi_boundary() { return; } let fixture = Fixture::new(); - let output = fixture.output("boundary-\u{1f642}", 135); + let output = fixture.output("boundary-\u{1f642}", 199); let relative = output.strip_prefix(&fixture.0).unwrap(); let dry_run = device_command(relative) .current_dir(&fixture.0) @@ -313,3 +313,182 @@ fn python_path_diagnostic_precedes_namespace_completion() { ); assert!(!files(&output).is_empty()); } + +#[test] +fn same_version_incremental_output_matches_fresh_typed_and_untyped_union() { + if !Path::new(WINDOWS_WINMD).exists() { + eprintln!("Skipping: Windows.winmd not found"); + return; + } + let fixture = Fixture::new(); + let roots = [ + "Windows.Foundation.Uri", + "Windows.Devices.Enumeration.DeviceInformation", + ]; + for pyi in [true, false] { + let generate = |output: &Path, roots: &[&str]| { + let mut command = command(output); + command.args(["--class-name", &roots.join(",")]); + if !pyi { + command.arg("--no-pyi"); + } + let output = command.output().unwrap(); + successful(&output); + assert!(!stderr(&output).contains(WARNING)); + }; + let fresh = fixture.output(&format!("fresh-{pyi}"), 120); + generate(&fresh, &roots); + let expected = files(&fresh); + for reverse in [false, true] { + let phased = fixture.output(&format!("phased-{pyi}-{reverse}"), 120); + let order = if reverse { [roots[1], roots[0]] } else { roots }; + for root in order { + generate(&phased, &[root]); + } + assert_eq!(files(&phased), expected); + } + assert!( + expected + .keys() + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "py" || extension == "pyi") + }) + .all(|path| path_length(path) <= 60) + ); + let stamp: serde_json::Value = + serde_json::from_slice(&expected[Path::new(".dynwinrt-generator.json")]).unwrap(); + assert_eq!(stamp["generator_version"], env!("CARGO_PKG_VERSION")); + } +} + +#[test] +fn synthetic_long_metadata_installs_through_a_utf16_output_root() { + let fixture = Fixture::new(); + let metadata = fixture.0.join("UnicodePaths.winmd"); + let namespace = "Windows.OutputPaths.UnicodeRoot"; + let names = ["First", "Second"] + .map(|suffix| format!("Options{}{suffix}", "LongMetadataName".repeat(8))); + let mut file = writer::File::new("PythonUnicodePaths"); + let base = file.TypeRef("System", "Enum"); + for name in &names { + file.TypeDef( + namespace, + name, + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + file.Field( + "value__", + &Type::I32, + FieldAttributes::Public | FieldAttributes::SpecialName | FieldAttributes::RTSpecialName, + ); + let member = file.Field( + "One", + &Type::named(namespace, name), + FieldAttributes::Public + | FieldAttributes::Static + | FieldAttributes::Literal + | FieldAttributes::HasDefault, + ); + file.Constant(writer::HasConstant::Field(member), &Value::I32(1)); + } + fs::write(&metadata, file.into_stream()).unwrap(); + let output = fixture.output("unicode-\u{1f642}", 150); + successful( + &command_with_metadata(&output, &metadata) + .args(["--namespace", namespace]) + .output() + .unwrap(), + ); + let context = dynwinrt_codegen::codegen::python::PythonProjectionContext::packaged( + names.iter().map(|name| { + dynwinrt_codegen::types::TypeIdentity::named( + dynwinrt_codegen::types::TypeIdentityKind::Enum, + namespace, + name, + ) + }), + ) + .unwrap(); + let generated = files(&output); + assert!( + generated + .keys() + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "py" || extension == "pyi") + }) + .all(|path| path_length(path) <= 60) + ); + for name in &names { + let identity = dynwinrt_codegen::types::TypeIdentity::named( + dynwinrt_codegen::types::TypeIdentityKind::Enum, + namespace, + name, + ); + let implementation = context.implementation_module(&identity); + let source = fs::read_to_string(output.join(format!("{implementation}.py"))).unwrap(); + assert!(source.contains(&format!("class {name}(")), "{source}"); + } + + let Some(python) = std::env::var_os("DYNWINRT_TEST_PYTHON") else { + return; + }; + let installed = fixture.0.join("installed"); + successful( + &Command::new(&python) + .args([ + "-m", + "pip", + "install", + "--no-deps", + "--no-cache-dir", + "--target", + ]) + .arg(&installed) + .arg(&output) + .env( + "PIP_INDEX_URL", + "https://packagefeedproxy.microsoft.io/pypi/simple/", + ) + .env_remove("PIP_EXTRA_INDEX_URL") + .output() + .unwrap(), + ); + let public_namespace = + dynwinrt_codegen::codegen::python::python_namespace_segments(namespace).join("."); + let code = format!( + "import importlib,sys; sys.path.insert(0, sys.argv[1]); \ + package=importlib.import_module('generated_bindings.{public_namespace}'); \ + first=getattr(package, {:?}); second=getattr(package, {:?}); \ + assert first is not second; assert first(1).value == second(1).value == 1", + names[0], names[1], + ); + successful( + &Command::new(&python) + .args(["-I", "-c", &code]) + .arg(&installed) + .output() + .unwrap(), + ); + let consumer = fixture.0.join("consumer.py"); + fs::write( + &consumer, + format!( + "from generated_bindings.{public_namespace} import {} as Options\n\ + value: Options = Options(1)\n", + names[0], + ), + ) + .unwrap(); + successful( + &Command::new(&python) + .args(["-m", "mypy", "--strict", "--no-incremental", "--cache-dir"]) + .arg(fixture.0.join("m")) + .arg(&consumer) + .env("MYPYPATH", &installed) + .output() + .unwrap(), + ); +} diff --git a/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs b/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs index b8ec9b5b..7b772fed 100644 --- a/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs +++ b/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs @@ -8,13 +8,15 @@ //! native nullable-reference contract. Inputs, implementation protocols and //! the runtime `.py` annotations are unchanged. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{InterfaceMeta, MethodMeta}; -use dynwinrt_codegen::types::TypeMeta; +use dynwinrt_codegen::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; const WINDOWS_WINMD: &str = r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; @@ -65,6 +67,10 @@ impl Generated { fn module(&self, name: &str) -> String { fs::read_to_string(self.0.join(name)).unwrap_or_else(|error| panic!("{name}: {error}")) } + + fn identity_module(&self, identity: TypeIdentity, extension: &str) -> String { + self.module(&format!("{}.{extension}", common::python_module(identity))) + } } fn assert_contains(text: &str, expected: &str) { @@ -192,8 +198,14 @@ fn stub_outputs_follow_the_nullability_policy() { let folder = generated.module("windows__storage__storage_folder.pyi"); let folder_py = generated.module("windows__storage__storage_folder.py"); let folder_view = generated.module("windows__storage__i_storage_folder.pyi"); - let headers = - generated.module("windows__web__http__headers__http_content_header_collection.pyi"); + let headers = generated.identity_module( + TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.Web.Http.Headers", + "HttpContentHeaderCollection", + ), + "pyi", + ); let properties = generated.module("windows__foundation__collections__property_set.pyi"); let json = generated.module("windows__data__json__json_object.pyi"); let accelerometer = generated.module("windows__devices__sensors__accelerometer.pyi"); @@ -409,19 +421,54 @@ fn reference_collection_elements_are_nullable_regardless_of_provenance() { ) else { return; }; - let files = - generated.module("windows__foundation__collections__i_vector_view_storage_file.pyi"); + let files = generated.identity_module( + TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IVectorView`1", + [TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.Storage", + "StorageFile", + )], + ), + "pyi", + ); let array = generated.module("windows__data__json__json_array.pyi"); let object = generated.module("windows__data__json__json_object.pyi"); - let resources = - generated.module("windows__application_model__resources__core__resource_map.pyi"); + let resources = generated.identity_module( + TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.ApplicationModel.Resources.Core", + "ResourceMap", + ), + "pyi", + ); let playlist = generated.module("windows__media__playback__media_playback_list.pyi"); - let observable = generated - .module("windows__foundation__collections__i_observable_vector_media_playback_item.pyi"); - let string_map_view = - generated.module("windows__foundation__collections__i_map_view_string_string.pyi"); - let string_map_view_py = - generated.module("windows__foundation__collections__i_map_view_string_string.py"); + let observable = generated.identity_module( + TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IObservableVector`1", + [TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.Media.Playback", + "MediaPlaybackItem", + )], + ), + "pyi", + ); + let map_view = TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IMapView`2", + [ + TypeMeta::String.type_identity(), + TypeMeta::String.type_identity(), + ], + ); + let string_map_view = generated.identity_module(map_view.clone(), "pyi"); + let string_map_view_py = generated.identity_module(map_view, "py"); // Collection interfaces carry no provenance. A view or iterator obtained // from a mutable collection can expose a null slot, so view item diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py index f0d74285..b1f4120f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py @@ -1,10 +1,10 @@ # Generated by dynwinrt-codegen — do not edit from .windows__foundation__uri import Uri # noqa: F401 from .windows__foundation__www_form_url_decoder import WwwFormUrlDecoder # noqa: F401 -from .windows__foundation__collections__i_iterator_i_www_form_url_decoder_entry import IID_IIterator_IWwwFormUrlDecoderEntry, IIterator_IWwwFormUrlDecoderEntry # noqa: F401 +from .windows__foundation__collections__i_ite_027702629a2c4eac import IID_IIterator_IWwwFormUrlDecoderEntry, IIterator_IWwwFormUrlDecoderEntry # noqa: F401 from .windows__foundation__i_stringable import IID_IStringable, IStringable # noqa: F401 from .windows__foundation__i_stringable import IStringableHandlers # noqa: F401 -from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IID_IUriRuntimeClassWithAbsoluteCanonicalUri, IUriRuntimeClassWithAbsoluteCanonicalUri # noqa: F401 -from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IUriRuntimeClassWithAbsoluteCanonicalUriHandlers # noqa: F401 +from .windows__foundation__i_uri_runtime_clas_6102c75aa36ada61 import IID_IUriRuntimeClassWithAbsoluteCanonicalUri, IUriRuntimeClassWithAbsoluteCanonicalUri # noqa: F401 +from .windows__foundation__i_uri_runtime_clas_6102c75aa36ada61 import IUriRuntimeClassWithAbsoluteCanonicalUriHandlers # noqa: F401 from .windows__foundation__i_www_form_url_decoder_entry import IID_IWwwFormUrlDecoderEntry, IWwwFormUrlDecoderEntry # noqa: F401 from .windows__foundation__i_www_form_url_decoder_entry import IWwwFormUrlDecoderEntryHandlers # noqa: F401 diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi index 2a61dbc6..4dc26d5d 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi @@ -1,10 +1,10 @@ # Generated by dynwinrt-codegen — do not edit from .windows__foundation__uri import Uri as Uri from .windows__foundation__www_form_url_decoder import WwwFormUrlDecoder as WwwFormUrlDecoder -from .windows__foundation__collections__i_iterator_i_www_form_url_decoder_entry import IID_IIterator_IWwwFormUrlDecoderEntry, IIterator_IWwwFormUrlDecoderEntry as IIterator_IWwwFormUrlDecoderEntry +from .windows__foundation__collections__i_ite_027702629a2c4eac import IID_IIterator_IWwwFormUrlDecoderEntry, IIterator_IWwwFormUrlDecoderEntry as IIterator_IWwwFormUrlDecoderEntry from .windows__foundation__i_stringable import IID_IStringable, IStringable as IStringable from .windows__foundation__i_stringable import IStringableHandlers as IStringableHandlers -from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IID_IUriRuntimeClassWithAbsoluteCanonicalUri, IUriRuntimeClassWithAbsoluteCanonicalUri as IUriRuntimeClassWithAbsoluteCanonicalUri -from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IUriRuntimeClassWithAbsoluteCanonicalUriHandlers as IUriRuntimeClassWithAbsoluteCanonicalUriHandlers +from .windows__foundation__i_uri_runtime_clas_6102c75aa36ada61 import IID_IUriRuntimeClassWithAbsoluteCanonicalUri, IUriRuntimeClassWithAbsoluteCanonicalUri as IUriRuntimeClassWithAbsoluteCanonicalUri +from .windows__foundation__i_uri_runtime_clas_6102c75aa36ada61 import IUriRuntimeClassWithAbsoluteCanonicalUriHandlers as IUriRuntimeClassWithAbsoluteCanonicalUriHandlers from .windows__foundation__i_www_form_url_decoder_entry import IID_IWwwFormUrlDecoderEntry, IWwwFormUrlDecoderEntry as IWwwFormUrlDecoderEntry from .windows__foundation__i_www_form_url_decoder_entry import IWwwFormUrlDecoderEntryHandlers as IWwwFormUrlDecoderEntryHandlers diff --git a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs index 775b7d90..4274ed55 100644 --- a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs +++ b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs @@ -13,7 +13,7 @@ use dynwinrt_codegen::meta::{ self, ImplementationDelegateMeta, InterfaceImplementationMetadata, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta, }; -use dynwinrt_codegen::types::{FieldMeta, TypeMeta}; +use dynwinrt_codegen::types::{FieldMeta, TypeIdentity, TypeIdentityKind, TypeMeta}; const WINDOWS_WINMD: &str = r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; @@ -1138,9 +1138,13 @@ fn implementation_cli_emits_background_instance_public_views() { output }; let stem = if language == "js" { - "IBackgroundTaskInstance" + "IBackgroundTaskInstance".to_string() } else { - "windows__application_model__background__i_background_task_instance" + common::python_module(TypeIdentity::named( + TypeIdentityKind::Interface, + "Windows.ApplicationModel.Background", + "IBackgroundTaskInstance", + )) }; let declarations = if language == "js" { "d.ts" } else { "pyi" }; artifacts.push(( @@ -1220,11 +1224,9 @@ fn implementation_public_python_views_type_check_without_internal_constructors() .map(|entry| entry.unwrap().path()) .find(|path| { path.extension().is_some_and(|extension| extension == "pyi") - && path - .file_name() + && std::fs::read_to_string(path) .unwrap() - .to_string_lossy() - .starts_with("typed_event_handler_background_task_registration_group") + .contains("TypedEventHandler_BackgroundTaskRegistrationGroup") }) .expect("transitive BackgroundTaskRegistrationGroup delegate facade"); let public_name = delegate_facade @@ -1237,7 +1239,7 @@ fn implementation_public_python_views_type_check_without_internal_constructors() .unwrap() .with_extension(""); assert!( - relative.to_string_lossy().len() <= 120, + relative.to_string_lossy().encode_utf16().count() <= 56, "public namespace path exceeded the flat-module budget: {}", relative.display() ); @@ -1251,8 +1253,8 @@ fn implementation_public_python_views_type_check_without_internal_constructors() }) .expect("facade import of its canonical implementation"); assert_eq!( - implementation.strip_prefix("windows__foundation__"), - Some(public_name.as_str()) + implementation.rsplit('_').next(), + public_name.rsplit('_').next() ); assert!(package.join(format!("{implementation}.pyi")).is_file()); assert!( From 9915d1c3451a6beaf51b57a7525f1914a92c8496 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 9 Oct 2026 15:19:33 +0800 Subject: [PATCH 2/3] Use stable namespace APIs in Python E2E consumers Migrate formatter interfaces, nested struct helpers and delegate constants away from long implementation filenames. Preserve all scenario assertions and verify the complete 56-case Python E2E matrix against the compact layout. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2016e084-e482-4076-abde-eb8c13baf510 --- tests/e2e/runners/py_runner.py | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index cdda977e..fe399e54 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -2970,10 +2970,8 @@ async def read_all(stream): ) formatter_module = importlib.import_module( - implementation_module_name( - pkg_name, - 'Windows.Globalization.NumberFormatting', - 'DecimalFormatter', + namespace_module_name( + pkg_name, 'Windows.Globalization.NumberFormatting' ) ) interface_values = [] @@ -3761,13 +3759,12 @@ def observe_value(sender, args): elif kind == 'nested_struct_runtime': from typing import get_type_hints - module = importlib.import_module( - implementation_module_name( - pkg_name, namespace, 'Direct3DSurfaceDescription' - ) + namespace_module = importlib.import_module( + namespace_module_name(pkg_name, namespace) ) - descriptor_type = getattr(module, 'Direct3DSurfaceDescription') - nested_type = getattr(module, 'Direct3DMultisampleDescription') + descriptor_type = getattr(namespace_module, 'Direct3DSurfaceDescription') + nested_type = getattr(namespace_module, 'Direct3DMultisampleDescription') + module = importlib.import_module(descriptor_type.__module__) pixel_format = generated_type(pkg_name, 'DirectXPixelFormat') pack = getattr(module, 'pack_direct3_d_surface_description') unpack = getattr(module, 'unpack_direct3_d_surface_description') @@ -3776,6 +3773,7 @@ def observe_value(sender, args): globalns={ **vars(module), 'DirectXPixelFormat': pixel_format, + 'Direct3DMultisampleDescription': nested_type, }, ) if ( @@ -3837,11 +3835,7 @@ def observe_value(sender, args): 'TypedEventHandler_IMemoryBufferReference_Object' ) delegate_module = importlib.import_module( - implementation_module_name( - pkg_name, - 'Windows.Foundation', - delegate_name, - ) + namespace_module_name(pkg_name, 'Windows.Foundation') ) delegate_iid = getattr( delegate_module, From ea37d985c24a988b6dedd5a6bc1a06efc626d93d Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 9 Oct 2026 15:56:44 +0800 Subject: [PATCH 3/3] Use supported setuptools underscore option names Replace deprecated build-base/bdist-dir options with build_base/bdist_dir while retaining compact hash-scoped paths. Update renderer assertions and packaging E2E cache checks; verify both deprecation warnings are gone and source/wheel installation still passes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2016e084-e482-4076-abde-eb8c13baf510 --- .../python/test_generated_python_long_paths.ps1 | 6 +++--- tools/dynwinrt-codegen/src/codegen/package.rs | 10 ++++++---- tools/dynwinrt-codegen/src/main.rs | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/eng/release/python/test_generated_python_long_paths.ps1 b/eng/release/python/test_generated_python_long_paths.ps1 index ab28883e..eb5941eb 100644 --- a/eng/release/python/test_generated_python_long_paths.ps1 +++ b/eng/release/python/test_generated_python_long_paths.ps1 @@ -64,7 +64,7 @@ try { $buildBaseMatch = Select-String ` -LiteralPath (Join-Path $source "setup.cfg") ` - -Pattern "^build-base\s*=\s*(.+)$" + -Pattern "^build_base\s*=\s*(.+)$" if (-not $buildBaseMatch) { throw "Generated setup.cfg does not define a scoped build cache" } @@ -121,7 +121,7 @@ try { } $newBuildBaseMatch = Select-String ` -LiteralPath (Join-Path $source "setup.cfg") ` - -Pattern "^build-base\s*=\s*(.+)$" + -Pattern "^build_base\s*=\s*(.+)$" $newBuildBase = $newBuildBaseMatch.Matches[0].Groups[1].Value.Trim() if ($newBuildBase -eq $initialBuildBase) { throw "Generated file layout change did not rotate the scoped build cache" @@ -154,7 +154,7 @@ try { if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $renamedBuildBaseMatch = Select-String ` -LiteralPath (Join-Path $source "setup.cfg") ` - -Pattern "^build-base\s*=\s*(.+)$" + -Pattern "^build_base\s*=\s*(.+)$" $renamedBuildBase = $renamedBuildBaseMatch.Matches[0].Groups[1].Value.Trim() if ($renamedBuildBase -eq $preRenameBuildBase) { throw "Output package rename did not rotate the scoped build cache" diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index fee77bfe..85a00ba5 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -96,10 +96,10 @@ pub fn render_python_setup_cfg(build_cache_key: &str) -> String { format!( "# Generated by dynwinrt-codegen — do not edit\n\ [build]\n\ - build-base = .b/{build_cache_key}\n\ + build_base = .b/{build_cache_key}\n\ \n\ [bdist_wheel]\n\ - bdist-dir = .b/{build_cache_key}/w\n" + bdist_dir = .b/{build_cache_key}/w\n" ) } @@ -365,7 +365,9 @@ mod tests { fn python_build_cache_is_layout_scoped() { let out = render_python_setup_cfg("0123456789abcdef"); - assert!(out.contains("build-base = .b/0123456789abcdef")); - assert!(out.contains("[bdist_wheel]\nbdist-dir = .b/0123456789abcdef/w")); + assert!(out.contains("build_base = .b/0123456789abcdef")); + assert!(out.contains("[bdist_wheel]\nbdist_dir = .b/0123456789abcdef/w")); + assert!(!out.contains("build-base")); + assert!(!out.contains("bdist-dir")); } } diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 658045eb..318c2572 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -10900,7 +10900,7 @@ mod tests { assert!( fs::read_to_string(output.join("setup.cfg")) .unwrap() - .contains(&format!("build-base = .b/{initial}")) + .contains(&format!("build_base = .b/{initial}")) ); let inventory = fs::read_to_string(output.join(PYTHON_GENERATED_INVENTORY)).unwrap(); assert!(inventory.lines().any(|line| line == "setup.cfg"));