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
2 changes: 2 additions & 0 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,8 @@ methods remain available for compatibility.

Generated `IReference<T>` values use `T | null` in JavaScript. Native values,
`null`, and generated `IReference_*` wrappers are accepted as inputs.
Collection factories take arrays of these inputs, typed as
`(T | null | IReference_*)[]`, not a scalar or a `null` container.
The same projection applies when `IReference<T>` appears inside a WinRT struct;
packing boxes the field automatically and unpacking returns the native value.

Expand Down
71 changes: 66 additions & 5 deletions tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@ use crate::types::TypeMeta;
// TypeScript type annotation helpers
// ======================================================================

/// Preserve top-level union/intersection precedence without regrouping nested types.
pub(crate) fn ts_array_type(element_type: &str) -> String {
let mut depth = 0usize;
for ch in element_type.chars() {
match ch {
'(' | '[' | '{' | '<' => depth += 1,
')' | ']' | '}' | '>' => depth = depth.saturating_sub(1),
'|' | '&' if depth == 0 => return format!("({element_type})[]"),
_ => {}
}
}
format!("{element_type}[]")
}

fn ts_param_type(context: &JavaScriptProjectionContext, typ: &TypeMeta) -> String {
match typ {
TypeMeta::Bool => "boolean".to_string(),
Expand Down Expand Up @@ -89,7 +103,7 @@ pub(crate) fn ts_param_type_dts(
return "Uint8Array | number[]".to_string();
}
let elem_ts = ts_param_type_safe(context, inner, known);
return format!("{}[]", elem_ts);
return ts_array_type(&elem_ts);
}
if let TypeMeta::Parameterized {
name, piid, args, ..
Expand All @@ -100,7 +114,7 @@ pub(crate) fn ts_param_type_dts(
if is_vector_like_piid(piid) || is_vector_like_name(name) {
if let Some(elem) = args.first() {
let elem_ts = ts_param_type_safe(context, elem, known);
return format!("{} | {}[]", base, elem_ts);
return format!("{} | {}", base, ts_array_type(&elem_ts));
}
}
// IMap<K,V>, IMapView<K,V> → also accept Map<K,V>
Expand Down Expand Up @@ -306,10 +320,57 @@ pub(crate) fn ts_array_element_type(inner: &TypeMeta, known_types: &HashSet<Stri
| TypeMeta::Enum { .. } => "number[]".to_string(),
TypeMeta::I64 | TypeMeta::U64 => "bigint[]".to_string(),
TypeMeta::Struct { name, .. } if name == "HResult" => "number[]".to_string(),
TypeMeta::Struct { name, .. } => format!("{}[]", name),
TypeMeta::Struct { name, .. } => ts_array_type(name),
TypeMeta::Object => "Array<DynWinRtValue | null>".to_string(),
TypeMeta::RuntimeClass { name, .. } if known_types.contains(name) => format!("{}[]", name),
TypeMeta::Interface { name, .. } if known_types.contains(name) => format!("{}[]", name),
TypeMeta::RuntimeClass { name, .. } if known_types.contains(name) => ts_array_type(name),
TypeMeta::Interface { name, .. } if known_types.contains(name) => ts_array_type(name),
_ => "DynWinRtValue[]".to_string(),
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn array_types_preserve_element_precedence() {
for (element, expected) in [
("number", "number[]"),
("string", "string[]"),
(
"number | null | IReference_UInt32",
"(number | null | IReference_UInt32)[]",
),
("Observable & Vector", "(Observable & Vector)[]"),
("(number | null)", "(number | null)[]"),
("(number | null)[]", "(number | null)[][]"),
("Map<string, number | null>", "Map<string, number | null>[]"),
("[number | null, string]", "[number | null, string][]"),
("{ value: number | null }", "{ value: number | null }[]"),
] {
assert_eq!(ts_array_type(element), expected);
}
assert_eq!(
ts_array_type(&ts_array_type("number | null")),
"(number | null)[][]"
);
}

#[test]
fn array_parameters_keep_byte_and_scalar_projections() {
for (element, expected) in [
(TypeMeta::U8, "Uint8Array | number[]"),
(TypeMeta::U32, "number[]"),
(TypeMeta::String, "string[]"),
] {
assert_eq!(
ts_param_type_dts(
&Default::default(),
&TypeMeta::Array(Box::new(element)),
&HashSet::new(),
),
expected,
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ pub(super) fn project_collection_helpers(
},
],
argument_kinds: vec![],
return_type: format!("{}[]", elem_ts),
return_type: ts_array_type(&elem_ts),
async_kind: AsyncKind::None,
is_static: false,
invoke_expr: String::new(),
Expand Down Expand Up @@ -281,7 +281,7 @@ pub(super) fn project_collection_helpers(
}),
params: vec![ProjectedParam {
name: "items".into(),
ts_type: format!("{}[]", elem_ts),
ts_type: ts_array_type(&elem_ts),
optional: false,
delegate_wrap: None,
}],
Expand Down Expand Up @@ -541,7 +541,7 @@ pub(super) fn project_collection_create(
}),
params: vec![ProjectedParam {
name: "items".into(),
ts_type: format!("{}[]", elem_ts),
ts_type: ts_array_type(&elem_ts),
optional: false,
delegate_wrap: None,
}],
Expand Down Expand Up @@ -620,7 +620,7 @@ pub(super) fn project_collection_create(
}),
params: vec![ProjectedParam {
name: "items".into(),
ts_type: format!("{}[]", elem_ts),
ts_type: ts_array_type(&elem_ts),
optional: false,
delegate_wrap: None,
}],
Expand Down Expand Up @@ -669,8 +669,8 @@ pub(super) fn project_collection_create(
deprecated: None, returns: None, params: vec![],
}),
params: vec![
ProjectedParam { name: "keys".into(), ts_type: format!("{}[]", key_ts), optional: false, delegate_wrap: None },
ProjectedParam { name: "values".into(), ts_type: format!("{}[]", val_ts), optional: false, delegate_wrap: None },
ProjectedParam { name: "keys".into(), ts_type: ts_array_type(&key_ts), optional: false, delegate_wrap: None },
ProjectedParam { name: "values".into(), ts_type: ts_array_type(&val_ts), optional: false, delegate_wrap: None },
],
argument_kinds: vec![],
return_type: iface.name.clone(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ use crate::codegen::winrt::shared::structs::{

use super::ir::*;
use super::method::{
ts_array_element_type, ts_param_type_dts, ts_param_type_safe, ts_return_type_safe,
ts_array_element_type, ts_array_type, ts_param_type_dts, ts_param_type_safe,
ts_return_type_safe,
};
use super::naming::{capitalize, infer_const_type, to_camel_case};
use super::signature::{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
//! - Enums as `export enum` (not `Object.freeze`)

use crate::codegen::winrt::javascript::ir::*;
use crate::codegen::winrt::javascript::method::ts_array_type;

/// Render a projected file as a `.d.ts` declaration.
pub fn render(file: &ProjectedFile) -> String {
Expand Down Expand Up @@ -526,7 +527,10 @@ fn render_member_dts(out: &mut String, member: &ProjectedMember) {
));
}
SymbolKind::CollectionToArray { element_type } => {
out.push_str(&format!("\n toArray(): {}[];\n", element_type));
out.push_str(&format!(
"\n toArray(): {};\n",
ts_array_type(element_type)
));
}
SymbolKind::IteratorNext { element_type } => {
out.push_str(&format!(
Expand Down
28 changes: 28 additions & 0 deletions tools/dynwinrt-codegen/tests/collection_factory_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,34 @@ fn string_collection_factory_declarations_remain_native_js_arrays() {
assert!(dts.contains("static create(keys: string[], values: string[]): Collection;"));
}

#[test]
fn nullable_collection_declarations_group_array_elements_in_every_role() {
let reference = TypeMeta::Parameterized {
namespace: "Windows.Foundation".into(),
name: "IReference`1".into(),
piid: "61c17706-2d65-11e0-9ae8-d48564015472".into(),
args: vec![TypeMeta::U32],
};
let array = "(number | null | IReference_UInt32)[]";
for piid in [VECTOR, OBSERVABLE_VECTOR] {
let (_, dts) = project_factory(piid, vec![reference.clone()]);
assert!(
dts.contains(&format!("static create(items: {array}):")),
"{dts}"
);
if piid == VECTOR {
assert!(dts.contains(&format!("toArray(): {array};")), "{dts}");
}
}
let (_, dts) = project_factory(MAP, vec![reference.clone(), reference]);
assert!(
dts.contains(&format!(
"static create(keys: {array}, values: {array}): Collection;"
)),
"{dts}"
);
}

#[test]
fn reference_factories_preserve_managed_nulls_before_querying_every_role() {
let class = TypeMeta::RuntimeClass {
Expand Down
Loading
Loading