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
119 changes: 118 additions & 1 deletion bindings/js/__test__/generated-unsafe-companion.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,125 @@

import test from 'ava'
import { spawnSync } from 'node:child_process'
import { lstatSync, readFileSync, readlinkSync, rmSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs'
import { lstatSync, readFileSync, readlinkSync, rmSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs'
import { basename, dirname, join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'

test.serial('generated IUIAutomation unsafe companion parses and registers without native calls', (t) => {
const winmd = process.env.DYNWINRT_WIN32_WINMD
t.truthy(winmd, 'DYNWINRT_WIN32_WINMD is required')
const packageRoot = resolve(process.cwd())
const output = mkdtempSync(join(packageRoot, 'target-generated-unsafe-uia-'))
const locks = ['dynwinrt-generation.lock', 'dynwinrt-lock'].map((suffix) =>
join(dirname(output), `.${basename(output)}.${suffix}`),
)

try {
const generation = spawnSync(
'cargo',
[
'run',
'--quiet',
'-p',
'dynwinrt-codegen',
'--',
'generate',
'--winmd',
winmd!,
'--class-name',
'Windows.Win32.UI.Accessibility.IUIAutomation',
'--output',
output,
],
{ cwd: resolve(packageRoot, '..', '..'), encoding: 'utf8', windowsHide: true },
)
t.is(generation.status, 0, generation.stderr)

const modulePath = join(output, 'com', 'unsafe', 'windows', 'win32', 'ui', 'accessibility', 'IUIAutomationUnsafe.js')
const syntax = spawnSync(process.execPath, ['--check', modulePath], { encoding: 'utf8', windowsHide: true })
t.is(syntax.status, 0, syntax.stderr)

const packageScope = join(output, 'node_modules', '@microsoft')
mkdirSync(packageScope, { recursive: true })
symlinkSync(packageRoot, join(packageScope, 'dynwinrt'), 'junction')
const assertions = [
"const assert = require('node:assert/strict')",
"const { readFileSync } = require('node:fs')",
"const { DynComRawStructLayout } = require('@microsoft/dynwinrt/com/unsafe/raw')",
"assert.equal(typeof IUIAutomationUnsafe, 'function')",
'assert.equal(IUIAutomationUnsafe.prototype.rectToVariant.length, 2)',
'assert.equal(IUIAutomationUnsafe.prototype.variantToRect.length, 2)',
"assert.equal(typeof IUIAutomationUnsafe.prototype.elementFromPoint, 'function')",
"assert.deepEqual(Object.keys(IUIAutomationUnsafe.support.methods[0].targets).sort(), ['arm64', 'i686', 'x64'])",
`const source = readFileSync(${JSON.stringify(modulePath)}, 'utf8')`,
'const descriptors = [...source.matchAll(/^const _layout\\d+ = DynComRawStructLayout.fromDescriptor\\((.+)\\);$/gm)].map(match => JSON.parse(JSON.parse(match[1])))',
'assert.ok(descriptors.length > 0)',
'for (const descriptor of descriptors) {',
" assert.deepEqual(Object.keys(descriptor).sort(), ['arm64', 'name', 'x64', 'x86'])",
' assert.ok(DynComRawStructLayout.fromDescriptor(JSON.stringify(descriptor)).byValueType())',
'}',
"const point = descriptors.find(descriptor => descriptor.name === 'Windows.Win32.Foundation.POINT')",
'assert.ok(point)',
'assert.equal(point.x86.size, 8)',
'assert.equal(point.x86.alignment, 4)',
'assert.deepEqual(point.x86, point.x64)',
'assert.deepEqual(point.x86, point.arm64)',
'assert.throws(() => DynComRawStructLayout.fromDescriptor(JSON.stringify({ ...point, i686: point.x86 })).byValueType(), /unknown key `i686`/)',
"console.log('uia-import-ok')",
].join('\n')
for (const [mode, load] of [
['commonjs', `const { IUIAutomationUnsafe } = require(${JSON.stringify(modulePath)})`],
[
'module',
"import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);\n" +
`import { IUIAutomationUnsafe } from ${JSON.stringify(pathToFileURL(join(output, 'com', 'unsafe', 'index.mjs')).href)}`,
],
]) {
const execution = spawnSync(process.execPath, [`--input-type=${mode}`, '--eval', `${load}\n${assertions}`], {
cwd: output,
encoding: 'utf8',
windowsHide: true,
})
t.is(execution.status, 0, `${mode}: ${execution.stderr}\n${execution.stdout}`)
t.regex(execution.stdout, /uia-import-ok/)
}

const consumer = join(output, 'consumer.ts')
writeFileSync(
consumer,
[
`import type { IUIAutomationUnsafe } from './com/unsafe/windows/win32/ui/accessibility/IUIAutomationUnsafe.js'`,
`import type { DynWinRtValue, DynComRawMemory } from '@microsoft/dynwinrt/com/unsafe/raw'`,
'declare const automation: IUIAutomationUnsafe',
'declare const value: DynWinRtValue',
'declare const storage: DynComRawMemory',
'automation.rectToVariant(value, storage)',
'automation.variantToRect(value, storage)',
'automation.elementFromPoint(value, storage)',
].join('\n'),
)
const tsc = spawnSync(
process.execPath,
[
join(packageRoot, 'node_modules', 'typescript', 'bin', 'tsc'),
'--noEmit',
'--strict',
'--module',
'Node16',
'--moduleResolution',
'Node16',
'--target',
'ES2022',
consumer,
],
{ cwd: packageRoot, encoding: 'utf8', windowsHide: true },
)
t.is(tsc.status, 0, `${tsc.stdout}\n${tsc.stderr}`)
} finally {
rmSync(output, { recursive: true, force: true })
for (const lock of locks) rmSync(lock, { force: true })
}
})

test.serial('generated safe COM and unsafe WinML companions preserve exact contracts', (t) => {
const winmd = process.env.DYNWINRT_WIN32_WINMD
Expand Down
11 changes: 11 additions & 0 deletions docs/architecture/classic-com-generated-unsafe.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ Methods keep their natural projected names:
context.getValueByName(...);
```

Parameter names retain their metadata spelling apart from identifier sanitization
and escaping JavaScript reserved or strict-mode restricted binding names (for
example, `var` becomes `var_`). Generation rejects transformed parameter collisions
and clashes with generated implementation bindings instead of emitting ambiguous
arguments. JavaScript argument expressions and TypeScript declarations use the
same escaped names.

Do not emit a class without the `Unsafe` suffix for an unsafe projection. Method names
need an `Unsafe` suffix only if safe and unsafe methods are ever placed on the
same class; the preferred design keeps them in separate companion classes.
Expand All @@ -118,6 +125,10 @@ Non-executable methods and their exact classifier reasons remain visible in

Codegen uses the same capability classifier as `com-capability-census`.

Runtime aggregate descriptors use the architecture keys `x86`, `x64`, and `arm64`.
Census and support-report target keys remain `i686`, `x64`, and `arm64`; this
serialization boundary does not change the native layouts or target capabilities.

### Safe complete

The complete inherited interface passes the existing safe semantic projection.
Expand Down
80 changes: 79 additions & 1 deletion tools/dynwinrt-codegen/src/codegen/com/capability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2413,7 +2413,12 @@ pub fn raw_aggregate_descriptor(
));
};
root.insert(
target.key().into(),
match target {
CensusTarget::I686 => "x86",
CensusTarget::X64 => "x64",
CensusTarget::Arm64 => "arm64",
}
.into(),
raw_layout_descriptor_value(variant, target, &mut Vec::new())?,
);
}
Expand Down Expand Up @@ -3424,6 +3429,79 @@ mod tests {
}
}

#[test]
fn raw_aggregate_descriptors_use_runtime_architectures_without_renaming_census_targets() {
for is_union in [false, true] {
let layout = RawNativeLayoutSet {
recursive: false,
variants: vec![RawNativeLayout {
architectures: 7,
kind: if is_union {
RawLayoutKind::Explicit
} else {
RawLayoutKind::Sequential
},
packing: RawPacking::Default,
declared_size: None,
fields: [("tag", RawNativeType::U32), ("value", RawNativeType::USize)]
.into_iter()
.map(|(name, typ)| RawNativeField {
name: name.into(),
typ: raw(typ, 0),
explicit_offset: is_union.then_some(0),
fixed_count: None,
bitfield: false,
flexible_array: false,
})
.collect(),
is_union,
}],
};
let (actual_union, descriptor) =
raw_aggregate_descriptor("Tests", "Record", &layout).unwrap();
assert_eq!(actual_union, is_union);
let descriptor: serde_json::Value = serde_json::from_str(&descriptor).unwrap();
assert_eq!(
descriptor
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect::<Vec<_>>(),
["arm64", "name", "x64", "x86"]
);
for (target, width) in [("x86", 4), ("x64", 8), ("arm64", 8)] {
assert_eq!(
descriptor[target]["size"],
if is_union { width } else { 2 * width }
);
assert_eq!(descriptor[target]["alignment"], width);
assert_eq!(descriptor[target]["fields"][1]["type"]["kind"], "usize");
if is_union {
assert_eq!(descriptor[target]["complete"], true);
assert!(descriptor[target]["fields"][1].get("offset").is_none());
} else {
assert_eq!(descriptor[target]["fields"][1]["offset"], width);
}
}
}
assert_eq!(CensusTarget::I686.key(), "i686");
assert_eq!(
serde_json::to_string(&CensusTarget::I686).unwrap(),
"\"i686\""
);
let methods =
classify_interface_methods(&raw_interface(Some(vec![raw_method(Vec::new())]))).unwrap();
assert_eq!(
methods[0]
.targets
.keys()
.map(String::as_str)
.collect::<Vec<_>>(),
["arm64", "i686", "x64"]
);
}

#[test]
fn method_capabilities_inherit_missing_interface_identity_and_root_blockers() {
for iid in ["", "00000000-0000-0000-0000-000000000000"] {
Expand Down
Loading
Loading