diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 76fcc044..04166d6b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -157,6 +157,11 @@ jobs: run: | .\bindings\py\.venv\Scripts\python.exe -m pytest bindings\py\tests -q .\bindings\py\.venv\Scripts\python.exe -m mypy.stubtest dynwinrt --allowlist bindings\py\stubtest_allowlist.txt --ignore-disjoint-bases + - name: Test generated Python long paths + run: | + .\eng\release\python\test_generated_python_long_paths.ps1 ` + -Python .\bindings\py\.venv\Scripts\python.exe ` + -Codegen .\target\release\dynwinrt-codegen.exe - name: Run E2E tests run: .\tests\e2e\e2e_test.ps1 -SkipBuild - name: Test JS TSFN lifecycle and queue handling diff --git a/bindings/py/README.md b/bindings/py/README.md index 0c4e2e1e..66cfa67b 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -150,7 +150,12 @@ button = project_as(raw_button, Button) the raw value or source wrapper remains valid. The returned wrapper owns the QueryInterface result, participates in the active `projected_lifetime_scope()`, and preserves the projection identity cache. -Incompatible types raise the ordinary WinRT `OSError`. +Classes with a verifiable default-interface IID remain valid projection +targets even when metadata exposes them only through `Object`/`IInspectable`. +Projection always performs QueryInterface, so a static-only declaration cannot +produce a wrapper unless the input actually implements that default interface. +Incompatible types raise the ordinary WinRT `OSError`. Static-only metadata +classes with no instance surface are not projection targets. Use `wrapper.as_interface(InterfaceClass)` when converting an existing wrapper to an interface view. Use `InterfaceClass.from_value(raw)` for a raw diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 20d60ff5..42432ff7 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -4,7 +4,7 @@ _T = TypeVar("_T", covariant=True) _P = TypeVar("_P", covariant=True) _Tracked = TypeVar("_Tracked") _Projected_co = TypeVar("_Projected_co", covariant=True) -_RuntimeClass = TypeVar("_RuntimeClass", bound="_DynWinRTRuntimeClass") +_ProjectableClass = TypeVar("_ProjectableClass", bound="_DynWinRTProjectableClass") class _DynWinRTProjector(Protocol[_Projected_co]): @@ -12,7 +12,10 @@ class _DynWinRTProjector(Protocol[_Projected_co]): def from_value(cls, obj: "DynWinRTValue") -> _Projected_co: ... -class _DynWinRTRuntimeClass: ... +class _DynWinRTProjectableClass: ... + + +class _DynWinRTRuntimeClass(_DynWinRTProjectableClass): ... __all__ = [ @@ -103,8 +106,8 @@ class ProjectedLifetimeScope: def projected_lifetime_scope() -> ProjectedLifetimeScope: ... def project_as( - value: object, wrapper_type: type[_RuntimeClass] -) -> _RuntimeClass: ... + value: object, wrapper_type: type[_ProjectableClass] +) -> _ProjectableClass: ... def release_projected(value: object) -> None: ... diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index b4dec891..8353ad20 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -247,7 +247,10 @@ def project_as(value, wrapper_type): 'project_as only accepts generated runtime classes; use ' 'Interface.from_value(raw) or wrapper.as_interface(Interface).' ) - if not getattr(wrapper_type, '_dynwinrt_runtime_class_type', False): + if not ( + getattr(wrapper_type, '_dynwinrt_runtime_class_type', False) + or getattr(wrapper_type, '_dynwinrt_projectable_class_type', False) + ): raise TypeError('project_as requires a generated runtime class type.') projector = getattr(wrapper_type, '_from_native', None) if not callable(projector): diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index 772f1fd1..b679e050 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -617,6 +617,20 @@ def test_project_as_borrows_input_and_returns_managed_projection(): raw.release() +def test_project_as_accepts_qi_only_generated_class(): + Wrapper = _projected_wrapper_type("ProjectAsQiOnlyWrapper") + del Wrapper._dynwinrt_runtime_class_type + Wrapper._dynwinrt_projectable_class_type = True + + with RoApartment(1): + raw = DynWinRTValue.activation_factory("Windows.Foundation.Uri") + projected = project_as(raw, Wrapper) + + assert projected._obj.identity_raw() == raw.identity_raw() + release_projected(projected) + raw.release() + + def test_project_as_rejects_invalid_values_and_types(): Wrapper = _projected_wrapper_type("ProjectAsValidationWrapper") diff --git a/eng/release/python/test_generated_python_long_paths.ps1 b/eng/release/python/test_generated_python_long_paths.ps1 new file mode 100644 index 00000000..da10eee4 --- /dev/null +++ b/eng/release/python/test_generated_python_long_paths.ps1 @@ -0,0 +1,175 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory = $true)][string]$Python, + [Parameter(Mandatory = $true)][string]$Codegen +) + +$ErrorActionPreference = "Stop" +$tempRoot = [System.IO.Path]::GetTempPath().TrimEnd("\") +$prefix = "dynwinrt-python-long-path-" +$paddingLength = 104 - $tempRoot.Length - 1 - $prefix.Length +if ($paddingLength -lt 8) { + throw "Temporary directory is too long for the generated Python path test" +} +$longSegment = $prefix + ("x" * $paddingLength) +$root = Join-Path $tempRoot $longSegment +if ($root.Length -ne 104) { + throw "Long-path test root must be 104 characters, got $($root.Length)" +} +$source = Join-Path $root "source\generated_bindings" +$wheelDirectory = Join-Path $root "wheels" +$install = Join-Path $root "installed" + +try { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Force -Path $wheelDirectory | Out-Null + + & $Codegen generate ` + --class-name Windows.Devices.Enumeration.DeviceInformationCustomPairing ` + --lang py ` + --output $source + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + $modules = Get-ChildItem -LiteralPath $source -File -Filter *.py + $tooLong = $modules | Where-Object { $_.BaseName.Length -gt 120 } + if ($tooLong) { + throw "Generated Python module exceeds 120 characters: $($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" + } + + $targetSymbol = + "TypedEventHandler_DeviceInformationCustomPairing_DevicePairingSetMembersRequestedEventArgs" + $shortModule = $modules | + Where-Object { + $_.BaseName -match "_[0-9a-f]{16}$" -and + (Select-String -LiteralPath $_.FullName -Pattern $targetSymbol -Quiet) + } | + Select-Object -First 1 + if (-not $shortModule) { + throw "Long-path fixture did not generate the expected typed event handler" + } + + $buildBaseMatch = Select-String ` + -LiteralPath (Join-Path $source "setup.cfg") ` + -Pattern "^build-base\s*=\s*(.+)$" + if (-not $buildBaseMatch) { + throw "Generated setup.cfg does not define a scoped build cache" + } + $initialBuildBase = $buildBaseMatch.Matches[0].Groups[1].Value.Trim() + $initialScopedCache = Join-Path $source $initialBuildBase + $cachedPackages = @( + (Join-Path $source "build\lib\generated_bindings"), + (Join-Path $initialScopedCache "lib\generated_bindings"), + (Join-Path $source ".venv\Lib\site-packages\generated_bindings"), + (Join-Path $source "venv\Lib\site-packages\generated_bindings"), + (Join-Path $source "env\Lib\site-packages\generated_bindings"), + (Join-Path $source ".tox\py\Lib\site-packages\generated_bindings"), + (Join-Path $source ".nox\py\Lib\site-packages\generated_bindings") + ) + foreach ($cachedPackage in $cachedPackages) { + New-Item -ItemType Directory -Force -Path $cachedPackage | Out-Null + foreach ($extension in @("py", "pyi")) { + Copy-Item ` + -LiteralPath (Join-Path $source "$($shortModule.BaseName).$extension") ` + -Destination $cachedPackage + } + } + $eggInfo = Join-Path $source "generated_bindings.egg-info" + New-Item -ItemType Directory -Force -Path $eggInfo | Out-Null + Set-Content -LiteralPath (Join-Path $eggInfo "SOURCES.txt") -Value $shortModule.BaseName + $dist = Join-Path $source "dist" + New-Item -ItemType Directory -Force -Path $dist | Out-Null + Set-Content -LiteralPath (Join-Path $dist "old-generated-bindings.whl") -Value $shortModule.BaseName + $pycache = Join-Path $source "__pycache__" + New-Item -ItemType Directory -Force -Path $pycache | Out-Null + Set-Content -LiteralPath (Join-Path $pycache "old.pyc") -Value $shortModule.BaseName + $preservedArtifacts = @( + (Join-Path $source "build"), + $initialScopedCache, + (Join-Path $source ".venv"), + (Join-Path $source "venv"), + (Join-Path $source "env"), + (Join-Path $source ".tox"), + (Join-Path $source ".nox"), + $dist, + $pycache, + $eggInfo + ) + + & $Codegen generate ` + --class-name Windows.Foundation.Uri ` + --lang py ` + --output $source + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + foreach ($artifact in $preservedArtifacts) { + if (-not (Test-Path -LiteralPath $artifact)) { + throw "Incremental generation deleted user artifact $artifact" + } + } + $newBuildBaseMatch = Select-String ` + -LiteralPath (Join-Path $source "setup.cfg") ` + -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" + } + foreach ($extension in @("py", "pyi")) { + if (-not (Test-Path -LiteralPath ( + Join-Path $source "$($shortModule.BaseName).$extension"))) { + throw "Unrelated incremental generation removed $($shortModule.BaseName).$extension" + } + } + + $preRenameBuildBase = $newBuildBase + $renamedSource = Join-Path (Split-Path $source -Parent) "renamed_bindings" + Move-Item -LiteralPath $source -Destination $renamedSource + $source = $renamedSource + $staleOldPackage = Join-Path $source ( + Join-Path $preRenameBuildBase "lib\generated_bindings") + New-Item -ItemType Directory -Force -Path $staleOldPackage | Out-Null + Set-Content ` + -LiteralPath (Join-Path $staleOldPackage "stale_old_package.py") ` + -Value "STALE = True" + Set-Content ` + -LiteralPath (Join-Path $staleOldPackage "stale_old_package.pyi") ` + -Value "STALE: bool" + + & $Codegen generate ` + --class-name Windows.Foundation.Uri ` + --lang py ` + --output $source + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $renamedBuildBaseMatch = Select-String ` + -LiteralPath (Join-Path $source "setup.cfg") ` + -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" + } + if (-not (Test-Path -LiteralPath $staleOldPackage)) { + throw "Output package rename deleted the old build cache" + } + + & $Python -m pip wheel $source --no-deps --wheel-dir $wheelDirectory + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $wheel = Get-ChildItem -LiteralPath $wheelDirectory -Filter *.whl -File | + Select-Object -First 1 + if (-not $wheel) { throw "Generated bindings wheel was not created" } + + & $Python -m pip install $wheel.FullName --no-deps --target $install + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") ` + --source $source ` + --install $install ` + --package renamed_bindings + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if (Test-Path -LiteralPath (Join-Path $install "generated_bindings")) { + throw "Renamed wheel retained the old generated_bindings package" + } +} 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 new file mode 100644 index 00000000..62c5d964 --- /dev/null +++ b/eng/release/python/verify_generated_python_install.py @@ -0,0 +1,78 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import argparse +import importlib +import sys +from pathlib import Path + + +def package_files(root: Path) -> set[Path]: + return { + path.relative_to(root) + for extension in ("*.py", "*.pyi") + for path in root.rglob(extension) + } + + +def generated_source_files(root: Path) -> set[Path]: + inventory = root / ".dynwinrt-generated-files" + files = { + Path(line) + for line in inventory.read_text(encoding="utf-8").splitlines() + if Path(line).suffix in {".py", ".pyi"} + } + invalid = [path for path in files if path.is_absolute() or ".." in path.parts] + if invalid: + raise RuntimeError(f"Generated inventory contains invalid paths: {invalid[:10]}") + missing = [path for path in files if not (root / path).is_file()] + if missing: + raise RuntimeError(f"Generated inventory references missing files: {missing[:10]}") + return files + + +def module_name(package: str, relative: Path) -> str: + parts = ( + relative.parts[:-1] + if relative.name == "__init__.py" + else relative.with_suffix("").parts + ) + return ".".join((package, *parts)) + + +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) + args = parser.parse_args() + + source = args.source.resolve() + installed = (args.install.resolve() / args.package) + expected = generated_source_files(source) + actual = package_files(installed) + missing = sorted(expected - actual) + if missing: + raise RuntimeError( + f"Installed package is missing {len(missing)} generated files: {missing[:10]}" + ) + unexpected = sorted(actual - expected) + if unexpected: + raise RuntimeError( + f"Installed package has {len(unexpected)} unexpected generated files: " + f"{unexpected[:10]}" + ) + + sys.path.insert(0, str(args.install.resolve())) + modules = { + module_name(args.package, path) + for path in expected + if path.suffix == ".py" + } + for name in sorted(modules): + importlib.import_module(name) + print(f"verified {len(expected)} files and imported {len(modules)} modules") + + +if __name__ == "__main__": + main() diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index 00f1c10b..5ce88b87 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -21,6 +21,10 @@ The Python distribution contains only the executable. Its wheels are do not install or invoke Cargo/Rust. Generated Python packages require CPython 3.11–3.14 and pin `dynwinrt` to the exact codegen version. +Generated Python module components longer than 120 characters use a stable +readable-prefix plus hash suffix. This keeps wheel build and installation paths +within practical Windows limits; public namespace imports remain unchanged. + ## Usage ```bash diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index af54b689..e3ecc0cc 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -50,6 +50,16 @@ pub fn render_python_pyproject(input: &PythonPackageManifestInput<'_>) -> String .iter() .map(|namespace| format!("\"{}.{}\"", input.import_name, namespace)), ); + let mut package_data = vec![format!( + "\"{}\" = [\"py.typed\", \"*.pyi\"]", + input.import_name + )]; + package_data.extend( + input + .namespace_packages + .iter() + .map(|namespace| format!("\"{}.{}\" = [\"*.pyi\"]", input.import_name, namespace)), + ); format!( "[build-system]\n\ requires = [\"setuptools>=68\"]\n\ @@ -66,15 +76,24 @@ pub fn render_python_pyproject(input: &PythonPackageManifestInput<'_>) -> String package-dir = {{ \"{import_name}\" = \".\" }}\n\ \n\ [tool.setuptools.package-data]\n\ - \"{import_name}\" = [\"py.typed\", \"*.pyi\", \"**/*.pyi\"]\n", + {package_data}\n", distribution_name = input.distribution_name, import_name = input.import_name, packages = packages.join(", "), + package_data = package_data.join("\n"), package_version = input.package_version, runtime_version = input.runtime_version, ) } +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" + ) +} + fn render_winrt_package(input: &BindingsPackageManifestInput<'_>) -> String { let mut out = String::new(); out.push_str("{\n"); @@ -278,6 +297,16 @@ mod tests { \"contoso_winrt.windows.foundation\"]" )); assert!(out.contains("dependencies = [\"dynwinrt==0.4.5\"]")); - assert!(out.contains("\"contoso_winrt\" = [\"py.typed\", \"*.pyi\", \"**/*.pyi\"]")); + assert!(out.contains("\"contoso_winrt\" = [\"py.typed\", \"*.pyi\"]")); + assert!(out.contains("\"contoso_winrt.windows\" = [\"*.pyi\"]")); + assert!(out.contains("\"contoso_winrt.windows.foundation\" = [\"*.pyi\"]")); + assert!(!out.contains("**/*.pyi")); + } + + #[test] + fn python_build_cache_is_layout_scoped() { + let out = render_python_setup_cfg("0123456789abcdef"); + + assert!(out.contains("build-base = .dynwinrt-build/0123456789abcdef")); } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs index 4aad45d4..517495f4 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -49,6 +49,7 @@ pub fn generate_class( "self._collection_obj" }; let projectable = super::super::has_projectable_default_interface(class); + let native_projectable = super::super::has_native_projector(class); let mut out = String::new(); // Header @@ -289,6 +290,8 @@ pub fn generate_class( } if projectable { out.push_str(" _dynwinrt_runtime_class_type = True\n"); + } else if native_projectable { + out.push_str(" _dynwinrt_projectable_class_type = True\n"); } out.push_str(&generate_python_constructor( @@ -688,10 +691,7 @@ pub fn generate_class( } // .as_interface() method for explicit, IID-checked interface projection. - if class - .default_interface - .as_ref() - .is_some_and(|interface| !interface.iid.is_empty() || interface.generic_piid.is_some()) + if super::super::has_projectable_default_interface(class) || !class.required_interfaces.is_empty() { out.push('\n'); @@ -1196,7 +1196,7 @@ fn generate_python_constructor( collection_uses_default: bool, ) -> String { let mut out = String::new(); - let projectable = super::super::has_projectable_default_interface(class); + let native_projectable = super::super::has_native_projector(class); let has_public_composition = class .constructors .iter() @@ -1263,7 +1263,7 @@ fn generate_python_constructor( }); out.push_str(" def __new__(cls, *args, **kwargs):\n"); - if projectable { + if native_projectable { out.push_str( " if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue):\n\ \x20 return _dynwinrt_projected_from_native(cls, args[0], '_set_native')\n", @@ -1368,7 +1368,7 @@ fn generate_python_constructor( )); out.push_str(" _dynwinrt_cache_projected(self)\n"); out.push('\n'); - if projectable { + if native_projectable { out.push_str(" @classmethod\n"); out.push_str(" def _from_native(cls, obj: DynWinRTValue):\n"); out.push_str(" return cls(obj)\n\n"); @@ -1420,7 +1420,7 @@ fn generate_python_constructor( " if getattr(self, '_dynwinrt_native_ready', False):\n\ \x20 return\n", ); - if projectable { + if native_projectable { out.push_str( " if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue):\n\ \x20 self._set_native(args[0])\n\ diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs index 0e61d5c7..8a509acc 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs @@ -23,10 +23,42 @@ pub use naming::{ }; pub(crate) fn has_projectable_default_interface(class: &crate::meta::ClassMeta) -> bool { - class - .default_interface - .as_ref() - .is_some_and(|interface| !interface.iid.is_empty() || interface.generic_piid.is_some()) + let Some(default_interface) = class.default_interface.as_ref() else { + return false; + }; + if default_interface.iid.is_empty() && default_interface.generic_piid.is_none() { + return false; + } + !default_interface.methods.is_empty() + || !class.required_interfaces.is_empty() + || !class.overridable_interfaces.is_empty() + || class.base_class.is_some() + || !class.constructors.is_empty() + || class.is_referenced_as_value + || class + .factory_interfaces + .iter() + .chain(class.static_interfaces.iter()) + .any(|interface| { + interface.methods.iter().any(|method| { + matches!( + method.return_type.as_ref(), + Some(crate::types::TypeMeta::RuntimeClass { + namespace, + name, + .. + }) if namespace == &class.namespace && name == &class.name + ) + }) + }) +} + +pub(crate) fn has_native_projector(class: &crate::meta::ClassMeta) -> bool { + has_projectable_default_interface(class) + || class + .default_interface + .as_ref() + .is_some_and(|interface| !interface.iid.is_empty()) } pub(crate) fn collect_referenced_delegate_names( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index fd9c017c..f01fe36a 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -22,6 +22,32 @@ thread_local! { static MODULE_LAYOUT: RefCell> = const { RefCell::new(None) }; } +const MAX_PYTHON_MODULE_COMPONENT_LENGTH: usize = 120; +const MODULE_HASH_HEX_LENGTH: usize = 16; + +fn stable_module_hash(value: &str) -> u64 { + let mut hash = 0xcbf29ce484222325_u64; + for byte in value.as_bytes() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x100000001b3); + } + hash +} + +fn shorten_module_component(value: &str) -> String { + if value.chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH { + return value.to_string(); + } + let prefix_length = MAX_PYTHON_MODULE_COMPONENT_LENGTH - MODULE_HASH_HEX_LENGTH - 1; + let prefix = value + .chars() + .take(prefix_length) + .collect::() + .trim_end_matches('_') + .to_string(); + format!("{prefix}_{:016x}", stable_module_hash(value)) +} + pub struct PythonModuleLayoutGuard; impl Drop for PythonModuleLayoutGuard { @@ -49,18 +75,7 @@ pub fn install_python_module_layout( let mut unique_modules = HashMap::new(); let mut owners = HashMap::::new(); for identity in identities { - let namespace = identity - .namespace - .split('.') - .filter(|segment| !segment.is_empty()) - .map(to_snake_case) - .collect::>() - .join("__"); - let module = if namespace.is_empty() { - to_snake_case(&identity.name) - } else { - format!("{namespace}__{}", to_snake_case(&identity.name)) - }; + let module = qualified_module_name(&identity.namespace, &identity.name); if let Some(existing) = owners.insert(module.clone(), identity.clone()) { return Err(format!( "Python module name collision: `{}.{}` and `{}.{}` both normalize to `{module}.py`", @@ -102,29 +117,24 @@ pub fn python_module_name(namespace: &str, name: &str) -> String { } fn qualified_module_name(namespace: &str, name: &str) -> String { - let namespace = namespace - .split('.') - .filter(|segment| !segment.is_empty()) - .map(to_snake_case) - .collect::>() - .join("__"); - if namespace.is_empty() { + let namespace = python_namespace_segments(namespace).join("__"); + shorten_module_component(&if namespace.is_empty() { to_snake_case(name) } else { format!("{namespace}__{}", to_snake_case(name)) - } + }) } pub fn python_namespace_segments(namespace: &str) -> Vec { namespace .split('.') .filter(|segment| !segment.is_empty()) - .map(to_snake_case) + .map(|segment| shorten_module_component(&to_snake_case(segment))) .collect() } pub fn python_public_module_name(name: &str) -> String { - to_snake_case(name) + shorten_module_component(&to_snake_case(name)) } pub fn python_public_qualified_module_name(namespace: &str, name: &str) -> String { @@ -234,7 +244,7 @@ pub fn to_snake_case_filename(name: &str) -> String { .borrow() .as_ref() .and_then(|layout| layout.unique_modules.get(name).cloned()) - .unwrap_or_else(|| to_snake_case(name)) + .unwrap_or_else(|| shorten_module_component(&to_snake_case(name))) }) } @@ -265,6 +275,36 @@ mod tests { ); } + #[test] + fn long_module_names_use_stable_hash_suffixes() { + 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, python_public_module_name(name)); + assert_ne!(shortened, python_public_module_name(&other)); + assert!(shortened.starts_with("typed_event_handler_media_playback_command_manager")); + } + + #[test] + fn installed_layout_shortens_implementation_and_public_modules_consistently() { + let name = "TypedEventHandler_MediaPlaybackCommandManager_MediaPlaybackCommandManagerAutoRepeatModeReceivedEventArgsAdditionalCompatibilitySuffix"; + let _guard = install_python_module_layout([PythonTypeIdentity { + namespace: "Windows.Foundation".into(), + name: name.into(), + }]) + .unwrap(); + let implementation = python_module_name("Windows.Foundation", name); + assert!(implementation.chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH); + assert_eq!(to_snake_case_filename(name), implementation); + assert!( + python_public_module_name(name).chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH + ); + } + #[test] fn snake_case_only_collapses_uint_word_boundaries() { assert_eq!(to_snake_case("MenuInt8"), "menu_int8"); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 2f930a09..fedae44d 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -67,6 +67,7 @@ from dynwinrt import (\n\ DynWinRTArray as DynWinRTArray, DynWinRTStruct as DynWinRTStruct,\n\ DynWinRtDelegate as DynWinRtDelegate, WinGUID as WinGUID,\n\ _DynWinRTProjector as _DynWinRTProjector,\n\ + _DynWinRTProjectableClass as _DynWinRTProjectableClass,\n\ _DynWinRTRuntimeClass as _DynWinRTRuntimeClass,\n\ )\n" ) @@ -464,12 +465,9 @@ pub fn generate_class_stub( .required_interfaces .iter() .any(|interface| interface.iid == "30d5a829-7fa4-4026-83bb-d75bae4ea99e"); - let supports_interface_projection = class - .default_interface - .as_ref() - .is_some_and(|interface| !interface.iid.is_empty() || interface.generic_piid.is_some()) - || !class.required_interfaces.is_empty(); let projectable = super::has_projectable_default_interface(class); + let native_projectable = super::has_native_projector(class); + let supports_interface_projection = projectable || !class.required_interfaces.is_empty(); let mut out = String::new(); out.push_str(HEADER); @@ -477,6 +475,8 @@ pub fn generate_class_stub( out.push_str(IMPORT_LINE); if projectable { out.push_str("from ._typing import _DynWinRTRuntimeClass\n"); + } else if native_projectable { + out.push_str("from ._typing import _DynWinRTProjectableClass\n"); } out.push_str("from typing import Protocol, Self\n"); if !has_constructor_stub_overload(class) { @@ -701,6 +701,8 @@ pub fn generate_class_stub( let mut bases = bases; if projectable { bases.push("_DynWinRTRuntimeClass".into()); + } else if native_projectable { + bases.push("_DynWinRTProjectableClass".into()); } out.push_str(&format!("\nclass {}({}):\n", class.name, bases.join(", "))); out.push_str(&super::docs::format_pydoc( @@ -1018,12 +1020,7 @@ fn emit_class_instance_stubs( ); } - if class - .default_interface - .as_ref() - .is_some_and(|interface| !interface.iid.is_empty() || interface.generic_piid.is_some()) - || !class.required_interfaces.is_empty() - { + if super::has_projectable_default_interface(class) || !class.required_interfaces.is_empty() { out.push('\n'); out.push_str( " def as_interface(self, interface_class: _DynWinRTProjector[_InterfaceT]) -> _InterfaceT: ...\n", diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 09a5f971..23e79565 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -1024,6 +1024,14 @@ fn generate_for_types( None }; + if lang == "py" && !dry_run { + let signature_types = meta::method_signature_type_names(winmd)?; + for class in &mut all_classes { + class.is_referenced_as_value = + signature_types.contains(&(class.namespace.clone(), class.name.clone())); + } + } + // Compute the set of interfaces `generate_js_files` will actually emit // (matches the class-name-collision + no-IID filter there). Everything // downstream — `known_types`, the barrel index, generated imports — must @@ -1162,7 +1170,6 @@ fn generate_for_types( } else { None }; - let (delegate_signatures, delegate_sig_refs, delegate_param_wraps) = project::build_delegate_signatures(&all_interfaces, &delegate_type_names, &known_types); @@ -3848,8 +3855,8 @@ fn merge_python_lazy_root_indexes( suppressed_names: &HashSet, ) -> String { let mut exports = BTreeMap::::new(); - collect_python_root_exports(existing, suppressed_names, &mut exports); collect_python_root_exports(generated, suppressed_names, &mut exports); + collect_python_root_exports(existing, suppressed_names, &mut exports); let mut out = String::from(GENERATED_PYTHON_HEADER); out.push_str("from importlib import import_module as _import_module\n\n"); @@ -3956,7 +3963,7 @@ fn merge_python_indexes( ) -> String { let mut imports = BTreeSet::new(); let mut exported_symbols = HashSet::new(); - for line in existing.lines().chain(generated.lines()) { + for line in generated.lines().chain(existing.lines()) { if line.starts_with("from .") { let (line, comment) = line .split_once(" #") @@ -4593,13 +4600,17 @@ fn copy_directory(source: &Path, destination: &Path) -> Result<(), String> { fn write_python_package_manifest(output_dir: &Path, final_output_dir: &Path) -> Result<(), String> { let manifest_path = output_dir.join("pyproject.toml"); - if manifest_path.exists() - && !python_inventory_contains(output_dir, Path::new("pyproject.toml"))? - { - return Err(format!( - "Refusing to overwrite existing non-generated manifest '{}'", - final_output_dir.join("pyproject.toml").display() - )); + let setup_path = output_dir.join("setup.cfg"); + for (path, name) in [ + (&manifest_path, "pyproject.toml"), + (&setup_path, "setup.cfg"), + ] { + if path.exists() && !python_inventory_contains(output_dir, Path::new(name))? { + return Err(format!( + "Refusing to overwrite existing non-generated manifest '{}'", + final_output_dir.join(name).display() + )); + } } let leaf = final_output_dir .file_name() @@ -4621,7 +4632,35 @@ fn write_python_package_manifest(output_dir: &Path, final_output_dir: &Path) -> runtime_version: version, namespace_packages: &namespace_packages, }); - write_file(&manifest_path, &manifest) + let build_cache_key = python_build_cache_key(output_dir, &import_name)?; + let setup = package::render_python_setup_cfg(&build_cache_key); + write_file(&manifest_path, &manifest)?; + write_file(&setup_path, &setup) +} + +fn python_build_cache_key(output_dir: &Path, import_name: &str) -> Result { + let mut hash = 0xcbf29ce484222325_u64; + for byte in b"package\0" + .iter() + .copied() + .chain(import_name.bytes()) + .chain(std::iter::once(b'\n')) + { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x100000001b3); + } + for path in collect_generated_python_files(output_dir, false, false)? { + let normalized = path + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); + for byte in normalized.bytes().chain(std::iter::once(b'\n')) { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x100000001b3); + } + } + Ok(format!("{hash:016x}")) } const PYTHON_GENERATED_INVENTORY: &str = ".dynwinrt-generated-files"; @@ -4658,8 +4697,11 @@ fn remove_all_generated_python_stubs(output_dir: &Path) -> Result<(), String> { .extension() .is_some_and(|extension| extension == "pyi") || relative.file_name().is_some_and(|name| name == "py.typed"); - let path = output_dir.join(relative); - if is_stub && path.is_file() { + let path = output_dir.join(&relative); + if is_stub + && path.is_file() + && is_generator_owned_python_source_file(output_dir, &relative)? + { fs::remove_file(&path) .map_err(|e| format!("Failed to remove {}: {}", path.display(), e))?; } @@ -4678,7 +4720,9 @@ fn remove_all_generated_python_stubs(output_dir: &Path) -> Result<(), String> { .file_type() .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))?; if file_type.is_dir() { - visit(&path)?; + if is_generated_python_namespace(&path)? { + visit(&path)?; + } } else if file_type.is_file() && path.extension().is_some_and(|extension| extension == "pyi") { @@ -4708,14 +4752,25 @@ fn clean_python_generated_output(output_dir: &Path) -> Result<(), String> { collect_generated_python_files(output_dir, false, false)? }; + let files = files + .into_iter() + .map(|relative| { + if !is_safe_relative_path(&relative) { + return Err(format!( + "Invalid path `{}` in {}", + relative.display(), + inventory_path.display() + )); + } + let owned = is_generator_owned_python_source_file(output_dir, &relative)?; + Ok((relative, owned)) + }) + .collect::, String>>()?; + let mut parent_dirs = HashSet::new(); - for relative in files { - if !is_safe_relative_path(&relative) { - return Err(format!( - "Invalid path `{}` in {}", - relative.display(), - inventory_path.display() - )); + for (relative, owned) in files { + if !owned { + continue; } let path = output_dir.join(&relative); if path.is_file() { @@ -4794,13 +4849,15 @@ fn collect_generated_python_files( .file_type() .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))?; if file_type.is_dir() { - visit( - root, - &path, - include_root_manifest, - include_root_marker, - files, - )?; + if is_generated_python_namespace(&path)? { + visit( + root, + &path, + include_root_manifest, + include_root_marker, + files, + )?; + } continue; } if !file_type.is_file() || entry.file_name() == PYTHON_GENERATED_INVENTORY { @@ -4809,7 +4866,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") => include_root_manifest && current == root, + Some("pyproject.toml" | "setup.cfg") => 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))? @@ -4843,6 +4900,65 @@ fn is_safe_relative_path(path: &Path) -> bool { .all(|component| matches!(component, std::path::Component::Normal(_))) } +fn is_generated_python_namespace(path: &Path) -> Result { + let init = path.join("__init__.py"); + if !init.is_file() { + return Ok(false); + } + Ok(fs::read_to_string(&init) + .map_err(|error| format!("Failed to inspect {}: {error}", init.display()))? + .starts_with(GENERATED_PYTHON_HEADER)) +} + +fn is_generator_owned_python_source_file( + output_dir: &Path, + relative: &Path, +) -> Result { + if !is_safe_relative_path(relative) { + return Ok(false); + } + let path = output_dir.join(relative); + if !path.is_file() { + return Ok(false); + } + let parent = relative + .parent() + .filter(|parent| !parent.as_os_str().is_empty()); + if parent.is_none() + && relative.file_name().is_some_and(|name| { + matches!( + name.to_str(), + Some("pyproject.toml" | "setup.cfg" | "py.typed") + ) + }) + { + return Ok(true); + } + if !relative + .extension() + .is_some_and(|extension| extension == "py" || extension == "pyi") + || !fs::read_to_string(&path) + .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))? + .starts_with(GENERATED_PYTHON_HEADER) + { + return Ok(false); + } + let Some(parent) = parent else { + return Ok(true); + }; + let mut current = output_dir.to_path_buf(); + for component in parent.components() { + let std::path::Component::Normal(component) = component else { + return Ok(false); + }; + current.push(component); + if !is_generated_python_namespace(¤t)? { + return Ok(false); + } + } + Ok(true) +} + fn collect_python_namespace_packages(output_dir: &Path) -> Result, String> { fn visit(root: &Path, current: &Path, packages: &mut Vec) -> Result<(), String> { for entry in fs::read_dir(current) @@ -4858,18 +4974,19 @@ fn collect_python_namespace_packages(output_dir: &Path) -> Result, S continue; } let path = entry.path(); - if path.join("__init__.py").is_file() { - let relative = path.strip_prefix(root).map_err(|e| { - format!("Failed to normalize package path {}: {}", path.display(), e) - })?; - packages.push( - relative - .components() - .map(|component| component.as_os_str().to_string_lossy()) - .collect::>() - .join("."), - ); + if !is_generated_python_namespace(&path)? { + continue; } + let relative = path.strip_prefix(root).map_err(|e| { + format!("Failed to normalize package path {}: {}", path.display(), e) + })?; + packages.push( + relative + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .collect::>() + .join("."), + ); visit(root, &path, packages)?; } Ok(()) @@ -6453,6 +6570,56 @@ mod tests { assert_eq!(normalize_python_package_name("123"), "_123"); } + #[test] + fn python_build_cache_key_ignores_user_directories() { + let output = test_directory("python-build-cache-key"); + fs::create_dir_all(&output).unwrap(); + fs::write( + output.join("generated.py"), + format!("{GENERATED_PYTHON_HEADER}VALUE = True\n"), + ) + .unwrap(); + let import_name = normalize_python_package_name( + output + .file_name() + .and_then(|name| name.to_str()) + .expect("test output name"), + ); + let initial = python_build_cache_key(&output, &import_name).unwrap(); + let cached = output + .join(".venv") + .join("Lib") + .join("site-packages") + .join("generated_bindings"); + fs::create_dir_all(&cached).unwrap(); + fs::write( + cached.join("legacy.py"), + format!("{GENERATED_PYTHON_HEADER}VALUE = True\n"), + ) + .unwrap(); + + assert_eq!( + python_build_cache_key(&output, &import_name).unwrap(), + initial + ); + assert_ne!( + python_build_cache_key(&output, "renamed_bindings").unwrap(), + initial + ); + + write_python_package_manifest(&output, &output).unwrap(); + write_python_generated_inventory(&output, true).unwrap(); + assert!( + fs::read_to_string(output.join("setup.cfg")) + .unwrap() + .contains(&format!("build-base = .dynwinrt-build/{initial}")) + ); + let inventory = fs::read_to_string(output.join(PYTHON_GENERATED_INVENTORY)).unwrap(); + assert!(inventory.lines().any(|line| line == "setup.cfg")); + assert!(!inventory.contains(".venv")); + fs::remove_dir_all(output).unwrap(); + } + #[test] fn stale_cleanup_removes_only_inventory_files() { let output = test_directory("stale-cleanup"); @@ -6482,6 +6649,47 @@ mod tests { fs::remove_dir_all(output).unwrap(); } + #[test] + fn python_output_transaction_preserves_user_directories() { + let output = test_directory("python-packaging-artifacts"); + let user_directories = [ + PathBuf::from("build").join("lib"), + PathBuf::from("dist"), + PathBuf::from("venv"), + PathBuf::from(".venv"), + PathBuf::from("env"), + PathBuf::from(".tox"), + PathBuf::from(".nox"), + PathBuf::from("__pycache__"), + PathBuf::from("generated_bindings.egg-info"), + PathBuf::from("generated_bindings.dist-info"), + ]; + fs::create_dir_all(&output).unwrap(); + for relative in &user_directories { + fs::create_dir_all(output.join(relative)).unwrap(); + fs::write(output.join(relative).join("cached.py"), "cached\n").unwrap(); + } + fs::write(output.join("existing.py"), "existing\n").unwrap(); + + let transaction = OutputTransaction::begin(&output).unwrap(); + assert!(transaction.stage_dir().join("existing.py").exists()); + for relative in &user_directories { + assert!( + transaction + .stage_dir() + .join(relative) + .join("cached.py") + .exists() + ); + } + transaction.commit().unwrap(); + + for relative in &user_directories { + assert!(output.join(relative).join("cached.py").exists()); + } + fs::remove_dir_all(output).unwrap(); + } + #[test] fn manual_python_manifest_is_not_overwritten() { let output = test_directory("manual-manifest"); @@ -6504,6 +6712,24 @@ mod tests { fs::remove_dir_all(output).unwrap(); } + #[test] + fn manual_python_build_config_is_not_overwritten() { + let output = test_directory("manual-build-config"); + fs::create_dir_all(&output).unwrap(); + fs::write(output.join("setup.cfg"), "[build]\nbuild-base = custom\n").unwrap(); + + let error = write_python_package_manifest(&output, &output) + .expect_err("manual build config must be preserved"); + + assert!(error.contains("Refusing to overwrite")); + assert!( + fs::read_to_string(output.join("setup.cfg")) + .unwrap() + .contains("build-base = custom") + ); + fs::remove_dir_all(output).unwrap(); + } + #[test] fn no_pyi_cleanup_preserves_manual_stubs() { let output = test_directory("stub-cleanup"); @@ -6592,8 +6818,10 @@ mod tests { let merged = merge_python_indexes(&existing, &generated, &HashSet::new()); - assert!(merged.contains("from .contoso__first import First, EventRegistrationToken, pack_event_registration_token")); - assert!(merged.contains("from .contoso__second import Second, TextSegment")); + assert!(merged.contains("from .contoso__first import First")); + assert!(merged.contains( + "from .contoso__second import Second, EventRegistrationToken, pack_event_registration_token, TextSegment" + )); assert_eq!(merged.matches("EventRegistrationToken").count(), 1); assert_eq!(merged.matches("pack_event_registration_token").count(), 1); } @@ -6610,7 +6838,7 @@ mod tests { assert!(merged.contains("from importlib import import_module as _import_module")); assert!(merged.contains("\"First\": (\".contoso__first\", \"First\")")); assert!(merged.contains("\"Second\": (\".contoso__second\", \"Second\")")); - assert!(merged.contains("\"Shared\": (\".contoso__first\", \"Shared\")")); + assert!(merged.contains("\"Shared\": (\".contoso__second\", \"Shared\")")); assert_eq!(merged.matches("\"Shared\": (").count(), 1); assert!(!merged.contains("from .contoso__first import")); assert!(merged.contains("def __getattr__(name):")); @@ -6630,13 +6858,38 @@ mod tests { fn generated_inventory_does_not_claim_nested_manual_metadata() { let output = test_directory("manual-metadata"); let nested = output.join("manual_package"); + let namespace = output.join("windows").join("foundation"); + let cached = output + .join("venv") + .join("Lib") + .join("site-packages") + .join("generated_bindings"); fs::create_dir_all(&nested).unwrap(); + fs::create_dir_all(&namespace).unwrap(); + fs::create_dir_all(&cached).unwrap(); fs::write( nested.join("pyproject.toml"), "[project]\nname = \"manual\"\n", ) .unwrap(); fs::write(nested.join("py.typed"), "").unwrap(); + fs::write( + output.join("windows").join("__init__.py"), + GENERATED_PYTHON_HEADER, + ) + .unwrap(); + fs::write(namespace.join("__init__.py"), GENERATED_PYTHON_HEADER).unwrap(); + fs::write( + namespace.join("uri.py"), + format!("{GENERATED_PYTHON_HEADER}class Uri: ...\n"), + ) + .unwrap(); + fs::write(cached.join("__init__.py"), GENERATED_PYTHON_HEADER).unwrap(); + fs::write( + cached.join("legacy.py"), + format!("{GENERATED_PYTHON_HEADER}class Legacy: ...\n"), + ) + .unwrap(); fs::write( output.join("generated.py"), format!("{GENERATED_PYTHON_HEADER}VALUE = True\n"), @@ -6647,8 +6900,52 @@ mod tests { let inventory = fs::read_to_string(output.join(PYTHON_GENERATED_INVENTORY)).unwrap(); assert!(inventory.contains("generated.py")); + assert!( + inventory + .lines() + .map(Path::new) + .any(|path| path == Path::new("windows").join("foundation").join("uri.py")) + ); + assert!(!inventory.contains("venv")); assert!(!inventory.contains("pyproject.toml")); assert!(!inventory.contains("py.typed")); + + let polluted_inventory = [ + PathBuf::from("generated.py"), + PathBuf::from("windows").join("__init__.py"), + PathBuf::from("windows") + .join("foundation") + .join("__init__.py"), + PathBuf::from("windows").join("foundation").join("uri.py"), + PathBuf::from("venv") + .join("Lib") + .join("site-packages") + .join("generated_bindings") + .join("__init__.py"), + PathBuf::from("venv") + .join("Lib") + .join("site-packages") + .join("generated_bindings") + .join("legacy.py"), + ]; + fs::write( + output.join(PYTHON_GENERATED_INVENTORY), + format!( + "{}\n", + polluted_inventory + .iter() + .map(|path| path.to_string_lossy()) + .collect::>() + .join("\n") + ), + ) + .unwrap(); + clean_python_generated_output(&output).unwrap(); + assert!(!output.join("generated.py").exists()); + assert!(!output.join("windows").exists()); + assert!(cached.join("__init__.py").exists()); + assert!(cached.join("legacy.py").exists()); + assert!(nested.join("pyproject.toml").exists()); fs::remove_dir_all(output).unwrap(); } } diff --git a/tools/dynwinrt-codegen/src/meta.rs b/tools/dynwinrt-codegen/src/meta.rs index f6db045e..40980266 100644 --- a/tools/dynwinrt-codegen/src/meta.rs +++ b/tools/dynwinrt-codegen/src/meta.rs @@ -148,6 +148,8 @@ pub struct ClassMeta { pub static_interfaces: Vec, pub has_default_constructor: bool, pub constructors: Vec, + /// The runtime class appears as a value in a loaded WinRT method signature. + pub is_referenced_as_value: bool, /// The runtime class declares MarshalingBehavior(Agile). pub is_agile: bool, /// XML doc summary (populated from sibling .xml). @@ -188,6 +190,63 @@ impl ClassMeta { } } +/// Collect every named type that appears in a WinRT method signature, including +/// types nested inside arrays and parameterized types. +pub fn method_signature_type_names(winmd_paths: &str) -> Result, String> { + fn collect(typ: &windows_metadata::Type, names: &mut HashSet<(String, String)>) { + match typ { + windows_metadata::Type::Name(name) => { + names.insert((name.namespace.clone(), name.name.clone())); + for generic in &name.generics { + collect(generic, names); + } + } + windows_metadata::Type::Array(inner) + | windows_metadata::Type::ArrayRef(inner) + | windows_metadata::Type::ConstRef(inner) + | windows_metadata::Type::PtrMut(inner, _) + | windows_metadata::Type::PtrConst(inner, _) + | windows_metadata::Type::ArrayFixed(inner, _) => collect(inner, names), + _ => {} + } + } + + let index = load_index(winmd_paths) + .ok_or_else(|| "Failed to load metadata method signatures".to_string())?; + let mut names = HashSet::new(); + for def in index.all() { + if !def + .flags() + .contains(windows_metadata::TypeAttributes::WindowsRuntime) + { + continue; + } + let generics = def + .generic_params() + .enumerate() + .map(|(index, _)| { + u16::try_from(index) + .map(windows_metadata::Type::Generic) + .map_err(|_| { + format!( + "Generic parameter index exceeds u16 for {}.{}", + def.namespace(), + def.name() + ) + }) + }) + .collect::, _>>()?; + for method in def.methods() { + let signature = method.signature(&generics); + collect(&signature.return_type, &mut names); + for typ in &signature.types { + collect(typ, &mut names); + } + } + } + Ok(names) +} + /// List all unique namespaces found in the given winmd files. pub fn list_namespaces(winmd_paths: &str) -> Vec { let index = match load_index(winmd_paths) { @@ -1216,6 +1275,7 @@ fn parse_class_from_index(index: &reader::Index, namespace: &str, name: &str) -> static_interfaces, has_default_constructor, constructors, + is_referenced_as_value: false, is_agile, doc: None, deprecated: None, diff --git a/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs b/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs index cedadd63..b61f7765 100644 --- a/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs +++ b/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs @@ -64,6 +64,7 @@ fn system_returned_class_keeps_only_internal_native_wrapping() { let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("def _from_native(cls, obj: DynWinRTValue):")); + assert!(py.contains("_dynwinrt_runtime_class_type = True")); assert!(!py.contains("from_value = classmethod"), "{py}"); assert!(py.contains("isinstance(args[0], DynWinRTValue)")); assert!(py.contains("SystemResult cannot be constructed directly")); @@ -77,11 +78,17 @@ fn system_returned_class_keeps_only_internal_native_wrapping() { } #[test] -fn static_only_class_has_no_native_projection_entry() { +fn static_only_class_has_only_qi_checked_projection_entry() { let class = ClassMeta { name: "ApiInformation".into(), namespace: "Windows.Foundation.Metadata".into(), full_name: "Windows.Foundation.Metadata.ApiInformation".into(), + default_interface: Some(InterfaceMeta { + name: "IApiInformation".into(), + namespace: "Windows.Foundation.Metadata".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), + ..Default::default() + }), static_interfaces: vec![factory("IApiInformationStatics", "IsTypePresent", None)], ..Default::default() }; @@ -91,31 +98,88 @@ fn static_only_class_has_no_native_projection_entry() { let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( - !py.contains("def _from_native(cls, obj: DynWinRTValue):"), + py.contains("def _from_native(cls, obj: DynWinRTValue):"), + "{py}" + ); + assert!( + py.contains("_dynwinrt_projectable_class_type = True"), "{py}" ); + assert!(py.contains("self._obj = obj.cast(IID_IApiInformation)")); + assert!(!py.contains("_dynwinrt_runtime_class_type = True"), "{py}"); assert!(!py.contains("from_value = classmethod"), "{py}"); - assert!(!py.contains("isinstance(args[0], DynWinRTValue)"), "{py}"); + assert!(py.contains("isinstance(args[0], DynWinRTValue)"), "{py}"); + assert!(!py.contains("def as_interface("), "{py}"); assert!(!pyi.contains("def from_value("), "{pyi}"); + assert!(!pyi.contains("_DynWinRTRuntimeClass"), "{pyi}"); + assert!(pyi.contains("_DynWinRTProjectableClass"), "{pyi}"); + assert!(!pyi.contains("def as_interface("), "{pyi}"); if Path::new(WINDOWS_WINMD).exists() { - let api_information = meta::parse_class( - WINDOWS_WINMD, - "Windows.Foundation.Metadata", - "ApiInformation", - ) - .expect("ApiInformation metadata"); - assert!(api_information.default_interface.is_none()); - let known = HashSet::from(["ApiInformation".into()]); - let py = python::generate_class(&api_information, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub( - &api_information, - &known, - &HashSet::new(), - &HashSet::new(), - ); - assert!(!py.contains("from_value = classmethod"), "{py}"); - assert!(!pyi.contains("def from_value("), "{pyi}"); + let signature_types = + meta::method_signature_type_names(WINDOWS_WINMD).expect("method signature metadata"); + let mut checked = 0; + for (namespace, name) in [ + ("Windows.Foundation.Metadata", "ApiInformation"), + ("Windows.System.Profile", "AnalyticsInfo"), + ("Windows.UI", "Colors"), + ("Windows.UI", "ColorHelper"), + ] { + let Some(mut class) = meta::parse_class(WINDOWS_WINMD, namespace, name) else { + continue; + }; + class.is_referenced_as_value = + signature_types.contains(&(namespace.to_string(), name.to_string())); + assert!( + !class.is_referenced_as_value, + "{namespace}.{name} is not static-only" + ); + let has_qi_default = class + .default_interface + .as_ref() + .is_some_and(|interface| !interface.iid.is_empty()); + checked += 1; + let known = HashSet::from([name.into()]); + let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = + python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + assert!( + !py.contains("from_value = classmethod"), + "{namespace}.{name}:\n{py}" + ); + assert!( + !py.contains("_dynwinrt_runtime_class_type = True"), + "{namespace}.{name}:\n{py}" + ); + assert_eq!( + py.contains("_dynwinrt_projectable_class_type = True"), + has_qi_default, + "{namespace}.{name}:\n{py}" + ); + assert_eq!( + py.contains("def _from_native(cls, obj: DynWinRTValue):"), + has_qi_default, + "{namespace}.{name}:\n{py}" + ); + assert!( + !py.contains("def as_interface("), + "{namespace}.{name}:\n{py}" + ); + assert!( + !pyi.contains("_DynWinRTRuntimeClass"), + "{namespace}.{name}:\n{pyi}" + ); + assert_eq!( + pyi.contains("_DynWinRTProjectableClass"), + has_qi_default, + "{namespace}.{name}:\n{pyi}" + ); + assert!( + !pyi.contains("def as_interface("), + "{namespace}.{name}:\n{pyi}" + ); + } + assert!(checked >= 2, "expected stock Windows static-only classes"); } } @@ -158,6 +222,88 @@ fn real_factory_constructors_reference_generated_private_helpers() { assert!(checked >= 2, "expected real constructor metadata"); } +#[test] +fn externally_returned_empty_class_keeps_native_projection() { + if !Path::new(WINDOWS_WINMD).exists() { + eprintln!("Skipping: Windows.winmd not found"); + return; + } + let mut class = meta::parse_class( + WINDOWS_WINMD, + "Windows.ApplicationModel.Background", + "DeviceWatcherTrigger", + ) + .expect("DeviceWatcherTrigger metadata"); + assert!(class.static_interfaces.is_empty()); + let signature_types = + meta::method_signature_type_names(WINDOWS_WINMD).expect("method signature metadata"); + assert!(signature_types.contains(&( + "Windows.ApplicationModel.Background".into(), + "DeviceWatcherTrigger".into() + ))); + class.is_referenced_as_value = true; + let known = HashSet::from(["DeviceWatcherTrigger".into()]); + let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + + assert!(py.contains("_dynwinrt_runtime_class_type = True"), "{py}"); + assert!( + py.contains("def _from_native(cls, obj: DynWinRTValue):"), + "{py}" + ); + assert!(pyi.contains("_DynWinRTRuntimeClass"), "{pyi}"); +} + +#[test] +fn externally_returned_empty_class_with_static_interface_keeps_native_projection() { + let mut class = ClassMeta { + name: "ExternallyReturned".into(), + namespace: "Contoso".into(), + full_name: "Contoso.ExternallyReturned".into(), + default_interface: Some(InterfaceMeta { + name: "IExternallyReturned".into(), + namespace: "Contoso".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), + ..Default::default() + }), + static_interfaces: vec![InterfaceMeta { + name: "IExternallyReturnedStatics".into(), + namespace: "Contoso".into(), + iid: "33333333-3333-3333-3333-333333333333".into(), + methods: vec![MethodMeta { + name: "IsSupported".into(), + return_type: Some(TypeMeta::Bool), + ..Default::default() + }], + ..Default::default() + }], + is_referenced_as_value: true, + ..Default::default() + }; + let known = HashSet::from(["ExternallyReturned".into()]); + + let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + assert!( + py.contains("def _from_native(cls, obj: DynWinRTValue):"), + "{py}" + ); + assert!(py.contains("_dynwinrt_runtime_class_type = True"), "{py}"); + assert!(pyi.contains("_DynWinRTRuntimeClass"), "{pyi}"); + + class.is_referenced_as_value = false; + let static_only = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + assert!(static_only.contains("def _from_native("), "{static_only}"); + assert!( + static_only.contains("_dynwinrt_projectable_class_type = True"), + "{static_only}" + ); + assert!( + !static_only.contains("_dynwinrt_runtime_class_type"), + "{static_only}" + ); +} + #[test] fn only_referenced_public_factory_metadata_becomes_a_constructor() { let activation_factory = factory( diff --git a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs index a4a5f906..2482e0da 100644 --- a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs +++ b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs @@ -20,6 +20,14 @@ fn runtime_class_generation_uses_projected_identity_cache() { name: "IWidget".into(), namespace: "Contoso".into(), iid: "11111111-1111-1111-1111-111111111111".into(), + methods: vec![MethodMeta { + name: "get_Name".into(), + raw_name: "get_Name".into(), + vtable_index: 6, + return_type: Some(TypeMeta::String), + is_property_getter: true, + ..Default::default() + }], ..Default::default() }), ..Default::default()