Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,7 @@ jobs:
$env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1'
cargo test -p dynwinrt-codegen `
--test implementation_naming_test `
--test python_constructor_diagnostics_test `
--test python_overload_legacy_compat_test `
--test python_released_implementation_test
- name: Test generated collection protocols
Expand Down
10 changes: 10 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,16 @@ composition, raise a class-named `TypeError` on normal construction and their
stubs expose no public constructor. Native return values still use the internal
`_from_native`/`DynWinRTValue` wrapping path.

When no constructor matches, the `TypeError` lists the supplied argument types
and keyword names, followed by all candidate signatures using the same Python
names and types as the stubs. For example, `Uri(url="https://example.com")`
reports `Uri(url=str)`, while `Uri(42)` reports `Uri(int)`; both list
`Uri(uri: str)` and `Uri(base_uri: str, relative_uri: str)`. Use `uri=`, or supply
both `base_uri=` and `relative_uri=` for the two-argument overload. Argument
values are not included in this diagnostic. Matching calls and errors from
native activation or argument conversion are unchanged; named factories such
as `Uri.create_uri(uri=...)` also retain their explicit signatures.

### Creating WinRT collections

`DynWinRTValue.create_vector(items, element_type)` and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1591,8 +1591,31 @@ fn generate_python_constructor(
context.class_name(class)
));
} else {
let mut seen = HashSet::new();
let signatures = candidates
.iter()
.map(|candidate| {
format!(
"{}({})",
context.class_name(class),
super::super::type_helpers::py_constructor_param_list(
&candidate.public_params,
context,
)
)
})
.filter(|signature| seen.insert(signature.clone()))
.collect::<Vec<_>>()
.join("; ");
let expected = serde_json::to_string(&format!("). Expected one of: {signatures}"))
.expect("constructor signature string");
// Avoid user-defined metaclass and string-formatting hooks on the failure path.
out.push_str(
" _type_name = type.__dict__['__name__'].__get__\n\
\x20 _received = ', '.join([_type_name(type(arg)) for arg in args] + ['='.join((name, _type_name(type(value)))) for name, value in kwargs.items()])\n",
);
out.push_str(&format!(
" raise TypeError(\"No matching constructor for {}\")\n\n",
" raise TypeError(\"No matching constructor for {}(\" + _received + {expected})\n\n",
context.class_name(class)
));
}
Expand Down
75 changes: 75 additions & 0 deletions tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,8 @@ fn only_referenced_public_factory_metadata_becomes_a_constructor() {

assert!(py.contains("type(self).create_result(_bound[0])"));
assert!(!py.contains("self._set_native(type(self).create()._obj)"));
assert!(py.contains("Expected one of: SystemResult(value: str)"));
assert!(!py.contains("Expected one of: SystemResult()"));
assert!(pyi.contains("def __init__(self, value: str) -> None: ..."));
assert!(!pyi.contains("def __init__(self) -> None: ..."));
}
Expand Down Expand Up @@ -407,6 +409,79 @@ fn numeric_constructor_overloads_dispatch_by_specificity() {
"I8 and I32 both project as one typed `int` constructor signature:\n{pyi}"
);
assert_eq!(pyi.matches(" @overload\n").count(), 0, "{pyi}");
assert_eq!(py.matches("SystemResult(value: int)").count(), 1, "{py}");
}

#[test]
fn constructor_diagnostics_use_public_python_parameters_and_types() {
let mut activation_factory = factory(
"ISystemResultFactory",
"Create",
Some(ParamMeta {
name: "baseUri".into(),
typ: TypeMeta::String,
direction: ParamDirection::In,
}),
);
activation_factory.methods[0].params.extend([
ParamMeta {
name: "outer".into(),
typ: TypeMeta::Object,
direction: ParamDirection::In,
},
ParamMeta {
name: "inner".into(),
typ: TypeMeta::Object,
direction: ParamDirection::Out,
},
]);
let class = ClassMeta {
name: "SystemResult".into(),
namespace: "Contoso".into(),
full_name: "Contoso.SystemResult".into(),
default_interface: Some(InterfaceMeta {
name: "ISystemResult".into(),
namespace: "Contoso".into(),
iid: "22222222-2222-2222-2222-222222222222".into(),
..Default::default()
}),
factory_interfaces: vec![activation_factory],
constructors: vec![
ConstructorMeta {
kind: ConstructorKind::DefaultActivation,
factory_interface: None,
},
ConstructorMeta {
kind: ConstructorKind::PublicComposition,
factory_interface: Some(TypeRef {
namespace: "Contoso".into(),
name: "ISystemResultFactory".into(),
kind: TypeKind::Interface,
}),
},
],
..Default::default()
};
let known = HashSet::from(["SystemResult".into()]);
let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new());
let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new());
let diagnostic = py
.lines()
.find(|line| line.contains("No matching constructor"))
.expect("constructor diagnostic");
assert!(diagnostic.contains("SystemResult()"), "{diagnostic}");
assert!(
diagnostic.contains("SystemResult(base_uri: str)"),
"{diagnostic}"
);
for hidden in ["baseUri", "outer", "inner", "Create", "IActivationFactory"] {
assert!(!diagnostic.contains(hidden), "{diagnostic}");
}
assert!(pyi.contains("def __init__(self) -> None: ..."), "{pyi}");
assert!(
pyi.contains("def __init__(self, base_uri: str) -> None: ..."),
"{pyi}"
);
}

#[test]
Expand Down
210 changes: 210 additions & 0 deletions tools/dynwinrt-codegen/tests/python_constructor_diagnostics_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

const WINDOWS_WINMD: &str =
r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd";

struct Generated(PathBuf);

impl Drop for Generated {
fn drop(&mut self) {
fs::remove_dir_all(&self.0).expect("remove generated constructor test package");
}
}

fn assert_success(output: Output) -> String {
assert!(
output.status.success(),
"exit {:?}\n{}\n{}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout).into_owned()
}

#[test]
fn generated_constructor_errors_preserve_valid_calls_and_native_failures() {
let winmd = std::env::var_os("DYNWINRT_WINDOWS_WINMD")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(WINDOWS_WINMD));
if !winmd.is_file() {
eprintln!("Skipping constructor diagnostics: Windows.winmd not found");
return;
}
let repo = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap();
let target = std::env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| repo.join("target"));
let package = format!("constructor_diagnostics_{}", std::process::id());
let generated = Generated(target.join(&package));
assert_success(
Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen"))
.args(["generate", "--winmd"])
.arg(winmd)
.args([
"--class-name",
"Windows.Foundation.Uri,Windows.Storage.Streams.Buffer,Windows.Storage.Streams.DataWriter,Windows.Storage.Streams.InMemoryRandomAccessStream",
"--lang",
"py",
"--output",
])
.arg(&generated.0)
.output()
.expect("generate constructor test package"),
);
let uri = fs::read_to_string(generated.0.join("windows__foundation__uri.py")).unwrap();
let stub = fs::read_to_string(generated.0.join("windows__foundation__uri.pyi")).unwrap();
for params in ["uri: str", "base_uri: str, relative_uri: str"] {
assert!(uri.contains(&format!("Uri({params})")), "{uri}");
assert!(
stub.contains(&format!("def __init__(self, {params}) -> None: ...")),
"{stub}"
);
}

let python = std::env::var_os("DYNWINRT_TEST_PYTHON")
.map(PathBuf::from)
.unwrap_or_else(|| {
let venv = repo.join(r"bindings\py\.venv\Scripts\python.exe");
if venv.is_file() {
venv
} else {
PathBuf::from("python")
}
});
let available = Command::new(&python)
.args([
"-c",
"from dynwinrt import RoApartment, projected_lifetime_scope, DynWinRTImplementationHandle",
])
.output()
.is_ok_and(|output| output.status.success());
assert!(
available || std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref() != Ok("1"),
"constructor diagnostics require the matching Python binding"
);
if !available {
eprintln!("Skipping native constructor diagnostics: matching binding not installed");
return;
}

let script = r#"
import inspect
import sys
from dynwinrt import RoApartment, projected_lifetime_scope
from PY_PACKAGE.windows.foundation import Uri
from PY_PACKAGE.windows.storage.streams import Buffer, DataWriter, InMemoryRandomAccessStream

uri_signatures = "Uri(uri: str); Uri(base_uri: str, relative_uri: str)"

def mismatch(call, received, signatures=uri_signatures):
try:
call()
except TypeError as error:
assert type(error) is TypeError
expected = f"No matching constructor for {received}. Expected one of: {signatures}"
assert str(error) == expected, str(error)
else:
raise AssertionError(f"accepted invalid call: {received}")

class NoRepr:
def __repr__(self):
raise AssertionError("constructor diagnostic must not format argument values")

__str__ = __repr__

class DerivedUri(Uri):
pass

class NoTypeName(type):
@property
def __name__(cls):
raise AssertionError("constructor diagnostic must not call metaclass hooks")

class CustomType(metaclass=NoTypeName):
pass

class NoFormat(str):
def __format__(self, spec):
raise AssertionError("constructor diagnostic must not format keyword objects")

with RoApartment(), projected_lifetime_scope():
modules_before = set(sys.modules)
mismatch(lambda: Uri(url="https://private.invalid/secret"), "Uri(url=str)")
mismatch(lambda: Uri(42), "Uri(int)")
assert set(sys.modules) == modules_before, "diagnostics must not import more modules"
mismatch(lambda: Uri(), "Uri()")
mismatch(lambda: Uri("a", "b", "c"), "Uri(str, str, str)")
mismatch(lambda: Uri(uri=42), "Uri(uri=int)")
mismatch(lambda: Uri("a", uri="b"), "Uri(str, uri=str)")
mismatch(lambda: Uri(base_uri="a"), "Uri(base_uri=str)")
mismatch(lambda: Uri(uri="a", relative_uri="b"), "Uri(uri=str, relative_uri=str)")
mismatch(lambda: Uri(NoRepr()), "Uri(NoRepr)")
mismatch(lambda: Uri(url=NoRepr()), "Uri(url=NoRepr)")
mismatch(lambda: Uri(CustomType()), "Uri(CustomType)")
mismatch(lambda: Uri(**{NoFormat("url"): CustomType()}), "Uri(url=CustomType)")
mismatch(lambda: DerivedUri(42), "Uri(int)")

base = "https://example.com/"
for create in (
lambda: Uri(base + "child"),
lambda: Uri(uri=base + "child"),
lambda: Uri(base, "child"),
lambda: Uri(base_uri=base, relative_uri="child"),
lambda: Uri(base, relative_uri="child"),
lambda: Uri(relative_uri="child", base_uri=base),
lambda: Uri.create_uri(uri=base + "child"),
lambda: Uri.create_with_relative_uri(base_uri=base, relative_uri="child"),
lambda: DerivedUri(base, relative_uri="child"),
):
uri = create()
assert uri.absolute_uri == base + "child"
assert str(inspect.signature(Uri)) == "(*args, **kwargs)"
assert Uri(uri._obj).absolute_uri == base + "child"

for create in (lambda: Buffer(3), lambda: Buffer(capacity=3)):
assert create().capacity == 3
mismatch(lambda: Buffer(2**32), "Buffer(int)", "Buffer(capacity: int)")
mismatch(lambda: Buffer(True), "Buffer(bool)", "Buffer(capacity: int)")

writer_signatures = "DataWriter(); DataWriter(output_stream: 'IOutputStream')"
mismatch(lambda: DataWriter(42), "DataWriter(int)", writer_signatures)
mismatch(lambda: DataWriter(stream=42), "DataWriter(stream=int)", writer_signatures)
with DataWriter() as writer:
writer.write_byte(65)
assert writer.unstored_buffer_length == 1
for keyword in (False, True):
with InMemoryRandomAccessStream() as stream:
writer = DataWriter(output_stream=stream) if keyword else DataWriter(stream)
with writer:
writer.write_byte(66)
assert writer.unstored_buffer_length == 1

try:
Uri("not a valid absolute URI")
except OSError as error:
assert error.winerror == -2147024809
assert "No matching constructor" not in str(error)
else:
raise AssertionError("native activation error was swallowed")

print("constructor-diagnostics-native-ok")
"#;
let output = assert_success(
Command::new(python)
.args(["-B", "-c", &script.replace("PY_PACKAGE", &package)])
.env("PYTHONPATH", &target)
.output()
.expect("run native constructor diagnostics"),
);
assert!(output.contains("constructor-diagnostics-native-ok"));
}
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ def __init__(self, *args, **kwargs):
if _bound is not None and (isinstance(_bound[0], _dynwinrt_symbol('windows__storage__streams__i_output_stream', 'IOutputStream')) or _dynwinrt_can_cast(_bound[0], IID_ARG_Windows_Storage_Streams_IOutputStream)):
self._set_native(type(self).create_data_writer(_bound[0])._obj)
return
raise TypeError("No matching constructor for DataWriter")
_type_name = type.__dict__['__name__'].__get__
_received = ', '.join([_type_name(type(arg)) for arg in args] + ['='.join((name, _type_name(type(value)))) for name, value in kwargs.items()])
raise TypeError("No matching constructor for DataWriter(" + _received + "). Expected one of: DataWriter(); DataWriter(output_stream: 'IOutputStream')")

@staticmethod
def _get_f_IDataWriterFactory():
Expand Down
4 changes: 3 additions & 1 deletion tools/dynwinrt-codegen/tests/snapshots/uri_py/uri.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ def __init__(self, *args, **kwargs):
if _bound is not None and isinstance(_bound[0], str) and isinstance(_bound[1], str):
self._set_native(type(self).create_with_relative_uri(_bound[0], _bound[1])._obj)
return
raise TypeError("No matching constructor for Uri")
_type_name = type.__dict__['__name__'].__get__
_received = ', '.join([_type_name(type(arg)) for arg in args] + ['='.join((name, _type_name(type(value)))) for name, value in kwargs.items()])
raise TypeError("No matching constructor for Uri(" + _received + "). Expected one of: Uri(uri: str); Uri(base_uri: str, relative_uri: str)")

@staticmethod
def _get_f_IUriRuntimeClassFactory():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ def __init__(self, *args, **kwargs):
if _bound is not None and isinstance(_bound[0], str):
self._set_native(type(self).create_www_form_url_decoder(_bound[0])._obj)
return
raise TypeError("No matching constructor for WwwFormUrlDecoder")
_type_name = type.__dict__['__name__'].__get__
_received = ', '.join([_type_name(type(arg)) for arg in args] + ['='.join((name, _type_name(type(value)))) for name, value in kwargs.items()])
raise TypeError("No matching constructor for WwwFormUrlDecoder(" + _received + "). Expected one of: WwwFormUrlDecoder(query: str)")

@staticmethod
def _get_f_IWwwFormUrlDecoderRuntimeClassFactory():
Expand Down
Loading