diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 51bf3b5d..6505a9ca 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -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 diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index 9c8ffb55..e5253af4 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -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. @@ -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. diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 04375dbb..2ed30ee9 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -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())?, ); } @@ -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::>(), + ["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::>(), + ["arm64", "i686", "x64"] + ); + } + #[test] fn method_capabilities_inherit_missing_interface_identity_and_root_blockers() { for iid in ["", "00000000-0000-0000-0000-000000000000"] { diff --git a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs index 1ca28a85..21cb3427 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -15,7 +15,7 @@ use super::capability::{ classify_interface_methods, metadata_set_identity_for_paths, parameter_manual_reasons, parameter_pointee_layouts, raw_aggregate_descriptor, }; -use super::javascript::naming::camel_case; +use super::javascript::naming::{camel_case, escape_js_binding_name}; pub const UNSAFE_SUPPORT_SCHEMA_VERSION: u32 = 12; @@ -865,7 +865,7 @@ fn render_method( if status == RawClassification::RawManualContract { return render_manual_method(method, capability, layouts, registration); } - let name = safe_identifier(&camel_case(&capability.projected_name)); + let name = safe_method_identifier(&camel_case(&capability.projected_name)); let args = method .params .iter() @@ -881,6 +881,33 @@ fn render_method( registration, ); } + let reserved = if exact_interface_outputs.is_empty() { + vec!["_out".to_string()] + } else { + [ + "_nativeArgs", + "_owners", + "_error", + "_cleanupErrors", + "_cleanup", + "_index", + "_prepareOwnedInterfaceOutput", + "_takeOwnedInterfaceOutput", + "_cleanupOwnedInterfaceOutput", + "WinGuid", + "Object", + "AggregateError", + ] + .into_iter() + .map(str::to_string) + .chain( + exact_interface_outputs + .iter() + .map(|(index, _, _)| format!("_ownedOutput{index}")), + ) + .collect() + }; + validate_parameter_identifiers(method, 0..method.params.len(), reserved)?; if !exact_interface_outputs.is_empty() { let mut js = format!( " /** @unsafe Exact owned COM output slots; each requested slot must start null. */\n {name}({args}) {{\n const _nativeArgs = [{}];\n const _owners = [];\n try {{\n _interface.method({}).invokeAll(this._obj, _nativeArgs);\n", @@ -1054,10 +1081,48 @@ fn render_exact_interface_output_call_method( return Err("Exact interface output flags and context must be input parameters".into()); } - let name = safe_identifier(&camel_case(&capability.projected_name)); + let name = safe_method_identifier(&camel_case(&capability.projected_name)); let flags_name = safe_identifier(&contract.flags_option_name); let synchronous_name = safe_identifier(synchronous_output_option_name); let semisynchronous_name = safe_identifier(semisynchronous_output_option_name); + validate_parameter_identifiers( + method, + contract.public_input_param_indices.iter().copied(), + [ + "options", + "Object", + "TypeError", + "undefined", + "Number", + "RangeError", + "AggregateError", + "WinGuid", + "_isSynchronous", + "_isSemisynchronous", + "_synchronousOutputRecord", + "_semisynchronousOutputRecord", + "_prepared", + "_nativeArgs", + "_owners", + "_owner", + "_error", + "_cleanupErrors", + "_cleanup", + "_index", + "__prepareExactWritableSpan", + "__validateStrategySpans", + "__strategyArgument", + "_takeOwnedInterfaceOutput", + "_cleanupOwnedInterfaceOutput", + ] + .into_iter() + .map(str::to_string) + .chain([ + flags_name.clone(), + synchronous_name.clone(), + semisynchronous_name.clone(), + ]), + )?; let method_args = if public_args.is_empty() { "options".into() } else { @@ -1246,7 +1311,51 @@ fn render_manual_method( } else { format!(" let {record_declarations};\n") }; - let name = safe_identifier(&camel_case(&capability.projected_name)); + validate_parameter_identifiers( + method, + 0..method.params.len(), + [ + "DynComRaw", + "Object", + "AggregateError", + "_prepared", + "_dispatch", + "_out", + "_method", + "_nativeArgs", + "_error", + "_cleanupErrors", + "_unsafeOutputs", + "_index", + "_unsafeOutput", + "_cleanup", + "_primary", + "_extracted", + "_directResult", + "_finishError", + "__prepareStrategy", + "__prepareWritableStorage", + "__strategyArgument", + "__assertRawContract", + "__validateStrategySpans", + "__activateStrategies", + "__markDispatchEntered", + "__finishStrategy", + "__failStrategy", + "__releaseExtracted", + "__attachUnsafeOutputs", + ] + .into_iter() + .map(str::to_string) + .chain( + prepared_indexes + .iter() + .map(|index| format!("_manualRecord{index}")), + ) + .chain((0..result_strategies.len()).map(|index| format!("_manualResult{index}"))) + .chain(method_contract.map(|_| "unsafeContract".to_string())), + )?; + let name = safe_method_identifier(&camel_case(&capability.projected_name)); let mut js = format!( " /** @unsafe Manual outbound ABI. Missing facts: {reason_text}. Required strategies: {requirement_text}. */\n {name}({}) {{\n const _prepared = [];\n const _dispatch = DynComRaw.__createDispatchState();\n{record_declarations} let _out;\n try {{\n", public_args.join(", ") @@ -1605,6 +1714,22 @@ fn render_return_conversion( } fn safe_identifier(name: &str) -> String { + escape_js_binding_name(sanitize_identifier(name)) +} + +fn safe_method_identifier(name: &str) -> String { + // Class member names are not bindings; retain the existing public spelling. + let mut value = sanitize_identifier(name); + if matches!( + value.as_str(), + "class" | "function" | "return" | "default" | "new" | "delete" | "this" + ) { + value.push('_'); + } + value +} + +fn sanitize_identifier(name: &str) -> String { let mut value = name .chars() .map(|character| { @@ -1618,15 +1743,48 @@ fn safe_identifier(name: &str) -> String { if value.is_empty() || value.as_bytes()[0].is_ascii_digit() { value.insert(0, '_'); } - if matches!( - value.as_str(), - "class" | "function" | "return" | "default" | "new" | "delete" | "this" - ) { - value.push('_'); - } value } +fn validate_parameter_identifiers( + method: &RawComMethod, + parameter_indices: impl IntoIterator, + generated_bindings: impl IntoIterator, +) -> Result<(), String> { + let mut bindings = BTreeMap::new(); + let identity = format!( + "{}.{}::{}", + method.declaring_namespace, method.declaring_interface, method.metadata_name + ); + for name in ["DynCom", "DynComRawPointer", "_interface", "_rawPointer"] + .into_iter() + .map(str::to_string) + .chain(generated_bindings) + { + if bindings + .insert(name.clone(), "generated binding".to_string()) + .is_some() + { + return Err(format!( + "{identity} has colliding generated binding `{name}`" + )); + } + } + for index in parameter_indices { + let param = method.params.get(index).ok_or_else(|| { + format!("{identity} has an out-of-range public parameter index {index}") + })?; + let name = safe_identifier(¶m.name); + let source = format!("parameter {index} (`{}`)", param.name); + if let Some(existing) = bindings.insert(name.clone(), source.clone()) { + return Err(format!( + "{identity} {source} collides with {existing} as JavaScript binding `{name}`" + )); + } + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -1729,6 +1887,161 @@ mod tests { } } + fn parameter_fixture(names: &[&str], manual: bool) -> Result { + let mut params = names + .iter() + .map(|name| param(name, raw(RawNativeType::U32, 0), RawParamDirection::In)) + .collect::>(); + if manual { + params.push(param( + "output", + raw(RawNativeType::Void, 2), + RawParamDirection::Out, + )); + } + generate_unsafe_interface_files_with_identity( + &interface(vec![method("Var", 3, params, raw(RawNativeType::Void, 0))]), + identity(), + ) + } + + #[test] + fn unsafe_parameters_escape_reserved_and_restricted_bindings() { + let names = [ + "var", + "const", + "let", + "for", + "catch", + "with", + "enum", + "implements", + "interface", + "package", + "private", + "yield", + "await", + "arguments", + "eval", + "debugger", + ]; + for manual in [false, true] { + let output = parameter_fixture(&names, manual).unwrap(); + let js = output.js.unwrap(); + let dts = output.dts.unwrap(); + for name in names { + assert!(js.contains(&format!("DynCom.u32({name}_)")), "{js}"); + assert!(dts.contains(&format!("{name}_: number")), "{dts}"); + } + assert!(js.contains("var(var_, const_, let_, for_")); + assert!(!js.contains("var_(var_")); + } + } + + #[test] + fn unsafe_parameters_preserve_spelling_and_sanitize_invalid_identifiers() { + let names = [ + "hwndMDI", + "dwReserved", + "URLValue", + "async", + "of", + "undefined", + "_unrelated", + "1value", + "value-with-hyphen", + "", + "$value", + ]; + let expected = [ + "hwndMDI", + "dwReserved", + "URLValue", + "async", + "of", + "undefined", + "_unrelated", + "_1value", + "value_with_hyphen", + "_", + "_value", + ]; + for manual in [false, true] { + let output = parameter_fixture(&names, manual).unwrap(); + let js = output.js.unwrap(); + let dts = output.dts.unwrap(); + for name in expected { + assert!(js.contains(&format!("DynCom.u32({name})")), "{js}"); + assert!(dts.contains(&format!("{name}: number")), "{dts}"); + } + } + } + + #[test] + fn unsafe_parameter_collisions_fail_closed_after_escaping_or_sanitizing() { + for names in [ + ["var", "var_"], + ["eval", "eval_"], + ["value", "value"], + ["", "_"], + ["1value", "_1value"], + ["value-with-hyphen", "value_with_hyphen"], + ["$value", "_value"], + ] { + for manual in [false, true] { + let error = parameter_fixture(&names, manual).unwrap_err(); + assert!(error.contains("Tests.ITest::Var"), "{error}"); + assert!(error.contains("parameter 1"), "{error}"); + assert!(error.contains("collides with parameter 0"), "{error}"); + } + } + } + + #[test] + fn unsafe_parameters_cannot_shadow_generated_bindings() { + for name in [ + "_out", + "_interface", + "_rawPointer", + "DynCom", + "DynComRawPointer", + ] { + let error = parameter_fixture(&[name], false).unwrap_err(); + assert!(error.contains("collides with generated binding"), "{error}"); + } + for name in [ + "_prepared", + "_dispatch", + "_out", + "_nativeArgs", + "_manualRecord1", + "DynComRaw", + "__prepareStrategy", + "_unsafeOutputs", + ] { + let error = parameter_fixture(&[name], true).unwrap_err(); + assert!(error.contains("collides with generated binding"), "{error}"); + } + let output = generate_unsafe_interface_files_with_identity( + &interface(vec![method( + "GetPointer", + 3, + vec![param( + "unsafeContract", + raw(RawNativeType::U32, 0), + RawParamDirection::In, + )], + raw(RawNativeType::Void, 1), + )]), + identity(), + ); + let error = output.unwrap_err(); + assert!( + error.contains("JavaScript binding `unsafeContract`"), + "{error}" + ); + } + #[test] fn partial_companion_emits_only_metadata_complete_methods() { let complete = method("GetURL", 3, Vec::new(), raw(RawNativeType::I32, 0)); @@ -1985,6 +2298,10 @@ mod tests { assert!(js.contains("DynComRawStructLayout.fromDescriptor")); assert!(js.contains("\\\"kind\\\":\\\"u32\\\"")); assert!(js.contains("\\\"offset\\\":0")); + assert!(js.contains("\\\"x86\\\":")); + assert!(js.contains("\\\"x64\\\":")); + assert!(js.contains("\\\"arm64\\\":")); + assert!(!js.contains("\\\"i686\\\":")); assert!(js.contains("_layout0.byValueType()")); assert!( output diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs index 6b95c41a..a27c9cf4 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs @@ -58,16 +58,25 @@ pub(super) fn js_param_name(raw: &str, index: usize) -> String { // so a Hungarian-prefixed acronym remainder like `hwndMDI` -> `MDI` casts // down to `mdi`, not a naive first-letter-only `mDI`. let out = lower_leading_acronym(stripped); + // Preserve the safe projection's existing escapes for contextual names. match out.as_str() { + "undefined" | "of" | "async" => format!("{out}_"), + _ => escape_js_binding_name(out), + } +} + +pub(in crate::codegen::com) fn escape_js_binding_name(name: String) -> String { + match name.as_str() { "class" | "return" | "function" | "default" | "this" | "new" | "delete" | "let" | "const" | "var" | "if" | "else" | "for" | "while" | "do" | "switch" | "case" - | "break" | "continue" | "true" | "false" | "null" | "undefined" | "in" | "of" - | "typeof" | "instanceof" | "throw" | "try" | "catch" | "finally" | "yield" | "async" - | "await" | "with" | "void" | "public" | "private" | "protected" | "package" | "static" - | "import" | "export" | "extends" | "super" | "arguments" => { - format!("{}_", out) + | "break" | "continue" | "true" | "false" | "null" | "in" | "typeof" | "instanceof" + | "throw" | "try" | "catch" | "finally" | "yield" | "await" | "with" | "void" + | "public" | "private" | "protected" | "package" | "static" | "import" | "export" + | "extends" | "super" | "arguments" | "eval" | "enum" | "implements" | "interface" + | "debugger" => { + format!("{name}_") } - _ => out, + _ => name, } } @@ -107,4 +116,65 @@ mod tests { // An acronym followed by a new word keeps the word capitalized. assert_eq!(js_param_name("IOHandle", 0), "ioHandle"); } + + #[test] + fn binding_names_escape_strict_reserved_and_restricted_identifiers() { + for name in [ + "await", + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "yield", + "let", + "static", + "implements", + "interface", + "package", + "private", + "protected", + "public", + "arguments", + "eval", + ] { + assert_eq!(escape_js_binding_name(name.into()), format!("{name}_")); + assert_eq!(js_param_name(name, 0), format!("{name}_")); + } + for name in ["undefined", "of", "async"] { + assert_eq!(escape_js_binding_name(name.into()), name); + assert_eq!(js_param_name(name, 0), format!("{name}_")); + } + } }