@nstudio/nativescript-compiler 9.2.0-alpha.13 → 9.2.0-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/css/worker.js +2 -2
  2. package/dist/driver/compile.js +4 -3
  3. package/dist/kotlin/arguments.js +7 -3
  4. package/dist/kotlin/assignment.js +3 -0
  5. package/dist/kotlin/builtins.js +15 -4
  6. package/dist/kotlin/class-constructor.js +3 -1
  7. package/dist/kotlin/class-methods.js +9 -2
  8. package/dist/kotlin/components.js +39 -14
  9. package/dist/kotlin/construction.js +4 -5
  10. package/dist/kotlin/conversion.js +19 -3
  11. package/dist/kotlin/core-api.js +31 -7
  12. package/dist/kotlin/declarations.js +8 -3
  13. package/dist/kotlin/expressions.js +10 -5
  14. package/dist/kotlin/library.js +2 -2
  15. package/dist/kotlin/modules.js +9 -4
  16. package/dist/kotlin/names.js +5 -2
  17. package/dist/kotlin/narrowing.js +2 -1
  18. package/dist/kotlin/optional-chains.js +24 -5
  19. package/dist/kotlin/overrides.js +7 -2
  20. package/dist/kotlin/placement.js +5 -4
  21. package/dist/kotlin/static-calls.js +17 -5
  22. package/dist/kotlin/translator.js +15 -39
  23. package/dist/kotlin/type-facts.js +3 -2
  24. package/dist/kotlin/types.js +6 -5
  25. package/dist/kotlin/untyped-values.js +7 -1
  26. package/dist/program/program.js +3 -3
  27. package/dist/semantics/apis/array.js +11 -0
  28. package/dist/semantics/classes.js +24 -0
  29. package/dist/semantics/config.js +2 -0
  30. package/dist/semantics/forms/by-name.js +30 -18
  31. package/dist/semantics/globals.js +8 -2
  32. package/dist/semantics/lang.js +4 -0
  33. package/dist/semantics/ledger.js +0 -24
  34. package/dist/semantics/platform-globals.js +0 -16
  35. package/dist/semantics/refusals.js +1 -1
  36. package/dist/semantics/runtime.js +2 -0
  37. package/dist/semantics/throws.js +7 -0
  38. package/dist/semantics/worker-state.js +41 -1
  39. package/dist/swift/assignment.js +3 -0
  40. package/dist/swift/builtins.js +20 -12
  41. package/dist/swift/class-methods.js +3 -1
  42. package/dist/swift/construction.js +5 -1
  43. package/dist/swift/conversion.js +1 -1
  44. package/dist/swift/expressions.js +2 -4
  45. package/dist/swift/from-any.js +5 -0
  46. package/dist/swift/global-calls.js +8 -1
  47. package/dist/swift/library.js +1 -1
  48. package/dist/swift/modules.js +2 -1
  49. package/dist/swift/object-classes.js +2 -1
  50. package/dist/swift/protocols.js +5 -16
  51. package/dist/swift/type-facts.js +2 -0
  52. package/dist/swift/types.js +7 -6
  53. package/dist/targets/android/build.js +9 -7
  54. package/dist/targets/ios/build.js +23 -8
  55. package/docs/cli/compile-ios.md +1 -1
  56. package/kit-android/generated/kotlin/org/nativescript/kit/file_system_file_system_access.kt +1 -1
  57. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_index.kt +1 -1
  58. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +6 -6
  59. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -1
  60. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +2 -2
  61. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_text_base_common.kt +2 -2
  62. package/kit-android/gradlew.bat +2 -2
  63. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Collections.kt +15 -6
  64. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Iterators.kt +1 -0
  65. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Promise.kt +5 -4
  66. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Workers.kt +39 -11
  67. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +13 -2
  68. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +0 -12
  69. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -39
  70. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +0 -44
  71. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +19 -2
  72. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +87 -22
  73. package/kit-apple/Sources/NativeScriptKit/Core/text.text-common.swift +9 -1
  74. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +13 -2
  75. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +26 -2
  76. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.liquid-glass-container.index.ios.swift +12 -2
  77. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.root-layout.root-layout-common.swift +46 -6
  78. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +37 -3
  79. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.split-view-common.swift +12 -1
  80. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +50 -6
  81. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.text-base-common.swift +13 -1
  82. package/kit-apple/Sources/NativeScriptKit/Runtime/Collections.swift +5 -1
  83. package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +13 -2
  84. package/kit-apple/Sources/NativeScriptKit/Runtime/Errors.swift +10 -2
  85. package/kit-apple/Sources/NativeScriptKit/Runtime/Functions.swift +57 -12
  86. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +12 -3
  87. package/kit-apple/Sources/NativeScriptKit/Runtime/Promise.swift +56 -29
  88. package/kit-apple/Sources/NativeScriptKit/Runtime/Realm.swift +92 -0
  89. package/kit-apple/Sources/NativeScriptKit/Runtime/Record.swift +25 -5
  90. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +13 -4
  91. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExpEngine.swift +14 -5
  92. package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +28 -6
  93. package/kit-apple/Sources/NativeScriptKit/Runtime/Threads.swift +2 -2
  94. package/kit-apple/Sources/NativeScriptKit/Runtime/Timers.swift +93 -47
  95. package/kit-apple/Sources/NativeScriptKit/Runtime/TypedArrays.swift +37 -9
  96. package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +6 -4
  97. package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +11 -2
  98. package/kit-apple/Sources/NativeScriptKit/Runtime/Workers.swift +680 -0
  99. package/package.json +1 -1
@@ -19,7 +19,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
19
19
  // rewrite, Vite's preprocessCSS, rework-css's parse).
20
20
  import fs, { readFileSync, writeFileSync } from 'node:fs';
21
21
  import { createRequire } from 'node:module';
22
- import { dirname, join, relative } from 'node:path';
22
+ import { dirname, isAbsolute, join, relative } from 'node:path';
23
23
  import { pathToFileURL } from 'node:url';
24
24
  const [outFile, cliLib, platform, ...stylesheets] = process.argv.slice(2);
25
25
  /** Components' stylesheets, by path: they have no file of their own. */
@@ -97,7 +97,7 @@ async function webpackSheets(configPath) {
97
97
  const resolveLoader = (name) => {
98
98
  for (const dir of loaderDirs) {
99
99
  try {
100
- return dir.startsWith('/') ? createRequire(join(dir, 'index.js')).resolve(join(dir, name)) : appRequire.resolve(name);
100
+ return isAbsolute(dir) ? createRequire(join(dir, 'index.js')).resolve(join(dir, name)) : appRequire.resolve(name);
101
101
  }
102
102
  catch { }
103
103
  }
@@ -116,10 +116,9 @@ export async function compile(o, build = new BuildContext()) {
116
116
  const included = adapter?.reach === 'entry' ? null : tsconfigIncluded(app, appDir);
117
117
  const reached = reachedFrom(adapter?.reach === 'entry' ? [entry] : files.filter((f) => !included || !/\.tsx?$/.test(f) || included.has(f)), importsOf);
118
118
  // A file only the other platform's files use (an Android audio worker) is no module of this build.
119
- // A worker's script runs in a worker, not as a module of the app; an iOS build refuses `new Worker`, so it starts none.
120
119
  // Transitively: a file only such files use is out too (an Android track engine its worker imports).
121
- // Android compiles worker scripts: the kit runs each on a worker thread.
122
- const leftOut = new Set([...(platform === 'android' ? [] : [...workerScripts].filter((w) => !usedBy.has(w))), ...platformSources.filter((f) => !reached.has(f))]);
120
+ // Both Android and iOS compile worker scripts: each kit runs them on their own worker threads.
121
+ const leftOut = new Set(platformSources.filter((f) => !reached.has(f)));
123
122
  for (let changed = true; changed;) {
124
123
  changed = false;
125
124
  for (const f of platformSources) {
@@ -539,6 +538,8 @@ export async function compile(o, build = new BuildContext()) {
539
538
  reach,
540
539
  properties,
541
540
  resolved,
541
+ workers: [...workerScripts],
542
+ aliased,
542
543
  lenient: lenientApp,
543
544
  assignFields: assignsFields,
544
545
  allowUnapplied,
@@ -123,9 +123,12 @@ export const argumentsMethods = {
123
123
  for (let k = 0; k < list.length; k++) {
124
124
  const a = list[k];
125
125
  if (restAt >= 0 && k >= restAt && appDeclared) {
126
- const calleeParam = ts.isCallExpression(e) ? functionTypeParts(this.typeOf(e.expression).replace(/^\((.*)\)\?$/, '$1'))?.params[restAt] : undefined;
126
+ const restDecl = params[restAt].valueDeclaration;
127
+ const erasedRest = this.library && !!restDecl && ts.isParameter(restDecl) && (!!restDecl.parent.typeParameters?.length || (ts.isClassLike(restDecl.parent.parent) && !!restDecl.parent.parent.typeParameters?.length));
128
+ const overloadedRest = !!impl && impl !== sig?.getDeclaration();
129
+ const calleeParam = ts.isCallExpression(e) && !erasedRest && !overloadedRest ? functionTypeParts(this.typeOf(e.expression).replace(/^\((.*)\)\?$/, '$1'))?.params[restAt] : undefined;
127
130
  const rest = calleeParam?.startsWith('JSArray<') && calleeParam.endsWith('>') ? calleeParam : this.restType(params[restAt]);
128
- out.push(this.packed(list.slice(k), rest, this.restSlot(e, rest.replace(/^JSArray<(.*)>$/, '$1'), params[restAt].valueDeclaration)));
131
+ out.push(this.packed(list.slice(k), rest, this.restSlot(e, rest.replace(/^JSArray<(.*)>$/, '$1'), restDecl)));
129
132
  break;
130
133
  }
131
134
  if (ts.isSpreadElement(a)) {
@@ -260,7 +263,8 @@ export const argumentsMethods = {
260
263
  if (literal && (this.readsArguments(literal) || literal.parameters.some((q) => q.dotDotDotToken || isThisParameter(q) || !ts.isIdentifier(q.name))))
261
264
  return null;
262
265
  const sigs = this.checker.getTypeAtLocation(e).getNonNullableType().getCallSignatures();
263
- if (sigs.length !== 1 || sigs[0].typeParameters?.length || sigs[0].getDeclaration()?.parameters.some((q) => q.dotDotDotToken))
266
+ const decl = sigs.length === 1 ? sigs[0].getDeclaration() : undefined;
267
+ if (sigs.length !== 1 || sigs[0].typeParameters?.length || decl?.parameters.some((q) => q.dotDotDotToken || isThisParameter(q)) || (decl && ts.isFunctionDeclaration(decl) && this.implicitThis(decl)))
264
268
  return null;
265
269
  const source = this.typeOf(e);
266
270
  const parts = this.scriptReadParts(source);
@@ -202,6 +202,9 @@ export const assignmentMethods = {
202
202
  isPromiseType(this.nativeOf(left.expression)));
203
203
  if (ts.isPropertyAccessExpression(left) && !this.library && this.isGlobalObject(left.expression))
204
204
  return `${RT.jsSet}(jsGlobalThis, ${kotlinString(left.name.text)}, ${this.untypedCallable(right)})`;
205
+ if (ts.isPropertyAccessExpression(left) && !this.library && this.typeOf(left.expression).replace(/\?$/, '') === 'JSWorker' && (left.name.text === 'onmessage' || left.name.text === 'onerror')) {
206
+ return `${RT.jsSet}(${this.expr(left.expression)}, ${kotlinString(left.name.text)}, ${this.untypedCallable(right)})`;
207
+ }
205
208
  // `record.key = v` of a `Record<string, T>`: its entry.
206
209
  const record = ts.isPropertyAccessExpression(left) ? /^JSRecord<(.*)>\??$/.exec(this.typeOf(left.expression)) : null;
207
210
  if (record && ts.isPropertyAccessExpression(left))
@@ -2,7 +2,7 @@
2
2
  import ts from 'typescript';
3
3
  import { MATH, MATH_OF_SPREAD } from "./library.js";
4
4
  import { mathFunction } from "../semantics/apis/math.js";
5
- import { arrayMember } from "../semantics/apis/array.js";
5
+ import { arrayMember, typedFlatPlan } from "../semantics/apis/array.js";
6
6
  import { collectionMember } from "../semantics/apis/mapset.js";
7
7
  import { argumentRunsConversion, numberMember } from "../semantics/apis/number.js";
8
8
  import { promiseMember } from "../semantics/apis/promise.js";
@@ -120,8 +120,19 @@ export const builtinMethods = {
120
120
  break;
121
121
  case 'toString':
122
122
  return `${t}.join()`;
123
- case 'flat':
124
- return e.arguments.length || !/^JSArray<JSArray</.test(this.typeOf(target)) ? `${t}.flatAny(${e.arguments[0] ? this.toNumber(e.arguments[0]) : ''})` : `${t}.flat()`;
123
+ case 'flat': {
124
+ const flat = typedFlatPlan(e, element, isUntyped(spelledType(element)));
125
+ switch (flat.kind) {
126
+ case 'default':
127
+ return /^JSArray<JSArray</.test(this.typeOf(target)) ? `${t}.flat()` : `${t}.flatAny()`;
128
+ case 'chain':
129
+ return `${t}${flat.suffix}`;
130
+ case 'depth': {
131
+ const expr = `${t}.flatAny(${this.toNumber(flat.arg)})`;
132
+ return flat.untyped ? expr : this.convert(expr, 'JSArray<Any?>', this.typeOf(e));
133
+ }
134
+ }
135
+ }
125
136
  case 'splice': {
126
137
  if (e.arguments.slice(2).some(ts.isSpreadElement))
127
138
  return `${t}.spliceAll(${e.arguments
@@ -478,7 +489,7 @@ export const builtinMethods = {
478
489
  /** A rejection handler: it takes the reason untyped, whatever its parameter declares. */
479
490
  rejectionHandler(e, ret) {
480
491
  if (!(ts.isArrowFunction(e) || ts.isFunctionExpression(e)))
481
- return this.isAny(e) ? this.fn(e, `(Any?) -> ${ret ?? 'Any?'}`) : this.fn(e);
492
+ return this.fn(e, `(Any?) -> ${ret ?? 'Any?'}`);
482
493
  if (!e.parameters.length)
483
494
  return this.closure(e, `(Any?) -> ${ret ?? this.returnTypeOf(e)}`);
484
495
  const p = e.parameters[0];
@@ -5,7 +5,7 @@ import { assignsTo, ident, kotlinString, optionalType, splitTopLevel, RT } from
5
5
  import { notesNull } from "../semantics/shapes.js";
6
6
  import { isConstant } from "../semantics/lang.js";
7
7
  import { boundNames } from "../semantics/ast.js";
8
- import { constructorOf } from "../semantics/classes.js";
8
+ import { constructorOf, rootErrorBase } from "../semantics/classes.js";
9
9
  export const classConstructorMethods = {
10
10
  constructorMembersCode(k) {
11
11
  const { cls, appBase, base, isError, lines } = k;
@@ -23,6 +23,8 @@ export const classConstructorMethods = {
23
23
  // `new HttpError(message, { cause })` of a class that declares no constructor: Error's.
24
24
  else if (isError && base !== 'JSAggregateError')
25
25
  lines.push(` constructor(message: Any? = null, options: Any? = null) : super(if (message == null) "" else ${RT.jsToString}(message), ${RT.jsGetIfPresent}(options, "cause"))`);
26
+ else if (appBase && (rootErrorBase(appBase, this.checker) ?? 'JSAggregateError') !== 'JSAggregateError')
27
+ lines.push(` constructor(message: Any? = null, options: Any? = null) : super(message, options)${level.length ? ' {' : ''}`, ...(level.length ? [...level, ' }'] : []));
26
28
  else if (k.collection) {
27
29
  lines.push(` constructor() : super()${level.length ? ' {' : ''}`, ...(level.length ? [...level, ' }'] : []));
28
30
  const mapArgs = /^JSMap<(.*)>$/.exec(k.collection)?.[1];
@@ -83,8 +83,15 @@ export const classMethodsMethods = {
83
83
  if (plugin && !this.library && !inherited.has(n) && !(kitRoot && this.core?.kitMember(kitRoot, n)) && !this.facts.isNamed(n))
84
84
  return;
85
85
  if (isStatic(m)) {
86
+ const clash = cls.members.some((x) => {
87
+ if (!isStatic(x) || !(ts.isPropertyDeclaration(x) || ts.isAccessor(x)) || !x.name || !ts.isIdentifier(x.name))
88
+ return false;
89
+ const p = x.name.text;
90
+ const cap = p[0].toUpperCase() + p.slice(1);
91
+ return n === `get${cap}` || n === `set${cap}` || (/^is[A-Z]/.test(p) && n === p);
92
+ });
86
93
  this.indent = ' ';
87
- k.statics.push(' ' + this.func(m, ident(n)));
94
+ k.statics.push(' ' + this.func(m, ident(n), clash ? `@JvmName("__fn_${n}") ` : ''));
88
95
  this.indent = ' ';
89
96
  return;
90
97
  }
@@ -212,7 +219,7 @@ export const classMethodsMethods = {
212
219
  root = up;
213
220
  if (root.parameters.length !== m.parameters.length)
214
221
  continue;
215
- dynMethods.push({ name: n, params: root.parameters.map((p) => this.paramType(p)), ret: this.returnTypeOf(root) });
222
+ dynMethods.push({ name: n, params: root.parameters.map((p) => this.paramType(p)), defaults: root.parameters.map((p) => (this.constantDefault(p) ? this.stored(p.initializer, p, this.paramType(p)) : undefined)), ret: this.returnTypeOf(root) });
216
223
  }
217
224
  }
218
225
  },
@@ -4,11 +4,11 @@ import { atLossSite, HELD_LOSS } from "../semantics/losses.js";
4
4
  import { ident, isFunctionType, isNullable, kotlinString, nullishType, optionalType, ownReturns, RT } from "./syntax.js";
5
5
  import { UNKEYED, definesDuringConstruction, implementedOptionalMembers, restrictsField, definedField } from "../semantics/shapes.js";
6
6
  import { extendsHeritage, hasModifier, isLibDeclaration, nonSuperStatements } from "../semantics/ast.js";
7
- import { implementedInterfaces } from "../semantics/lang.js";
7
+ import { implementedInterfaces, isEmittedInterface } from "../semantics/lang.js";
8
8
  import { isCoreDeclaration } from "../program/core-facts.js";
9
9
  import { isStatic } from "../semantics/throws.js";
10
10
  import { isUntyped, spelledType } from "../semantics/types.js";
11
- import { COLLECTION_OVERRIDE_METHODS, collectionBaseInfo } from "../semantics/classes.js";
11
+ import { COLLECTION_OVERRIDE_METHODS, collectionBaseInfo, ownClassMember, redeclaredMember } from "../semantics/classes.js";
12
12
  export const componentMethods = {
13
13
  /** A static field the module's statements initialize (`classDeclCode`'s statics): nullable until they run. */
14
14
  heldUntilModuleRuns(m) {
@@ -311,6 +311,7 @@ export const componentMethods = {
311
311
  /** The interfaces a class implements, named or met, that are Kotlin interfaces it implements; `witnesses` gets the adapters its methods need. */
312
312
  implementedProtocols(cls, witnesses, notOverrides) {
313
313
  const implemented = implementedInterfaces(this.checker, cls)
314
+ .filter((i) => isEmittedInterface(this.checker.getTypeAtLocation(i)))
314
315
  .filter((i) => !isLibDeclaration(this.checker.getTypeAtLocation(i).getSymbol()?.declarations?.[0]))
315
316
  // An interface of a module that is not translated (a package's `types.ts`, which declares only types) is no Kotlin interface.
316
317
  .filter((i) => !this.untranslatedInterface(i))
@@ -395,20 +396,44 @@ export const componentMethods = {
395
396
  protocolWitnesses(cls, decl, name, out, notOverrides) {
396
397
  if (!decl || !this.protocols.has(name))
397
398
  return true;
398
- const own = (name) => cls.members.find((x) => x.name?.getText() === name);
399
399
  const added = [];
400
400
  const skipped = [];
401
- for (const req of decl.members) {
402
- const name = req.name?.getText();
403
- const m = name ? own(name) : undefined;
401
+ for (const req of this.withInherited(decl, decl.members)) {
402
+ const memberName = req.name?.getText();
403
+ const m = memberName ? ownClassMember(cls, memberName, this.checker) : undefined;
404
404
  // A writable field the interface erases to any value, which a field typed by the class's type parameter can't override.
405
- if (name && ts.isPropertySignature(req) && !hasModifier(req, ts.SyntaxKind.ReadonlyKeyword) && this.isAny(req)) {
406
- const field = m ?? cls.members.find(ts.isConstructorDeclaration)?.parameters.find((p) => ts.isIdentifier(p.name) && p.name.text === name && ts.getModifiers(p)?.length);
407
- const t = field && (ts.isPropertyDeclaration(field) || ts.isParameter(field) || ts.isGetAccessorDeclaration(field) || ts.isSetAccessorDeclaration(field)) ? this.checker.getTypeAtLocation(field.name) : undefined;
405
+ if (memberName && ts.isPropertySignature(req) && !hasModifier(req, ts.SyntaxKind.ReadonlyKeyword) && this.isAny(req)) {
406
+ const t = m && (ts.isPropertyDeclaration(m) || ts.isParameter(m) || ts.isGetAccessorDeclaration(m) || ts.isSetAccessorDeclaration(m)) ? this.checker.getTypeAtLocation(m.name) : undefined;
408
407
  if (!this.ledger.genericsReified && t && t.flags & ts.TypeFlags.TypeParameter && t.symbol?.declarations?.[0]?.parent === cls)
409
- throw this.limit(field, 'generic-field-erased', "a field typed by a generic class's type parameter, met as a generic interface's writable field");
408
+ throw this.limit(m, 'generic-field-erased', "a field typed by a generic class's type parameter, met as a generic interface's writable field");
410
409
  }
411
- if (!name || !m || !ts.isMethodSignature(req))
410
+ if (memberName && m && ts.isPropertySignature(req)) {
411
+ if (!this.library) {
412
+ if (ts.isMethodDeclaration(m))
413
+ return false;
414
+ const expected = req.questionToken ? optionalType(this.typeOf(req)) : this.typeOf(req);
415
+ const baseField = redeclaredMember(m, this.checker);
416
+ const actual = ts.isGetAccessorDeclaration(m)
417
+ ? this.returnTypeOf(m)
418
+ : baseField
419
+ ? this.overUntypedField(m)
420
+ ? 'Any?'
421
+ : this.typeOf(baseField.name)
422
+ : ts.isPropertyDeclaration(m)
423
+ ? this.states.lenientNullField(m)
424
+ ? optionalType(this.typeOf(m.name))
425
+ : this.typeOf(m.name)
426
+ : ts.isParameter(m)
427
+ ? this.states.mayBeNull(m)
428
+ ? optionalType(this.typeOf(m.name))
429
+ : this.typeOf(m.name)
430
+ : null;
431
+ if (actual !== null && actual !== expected)
432
+ return false;
433
+ }
434
+ continue;
435
+ }
436
+ if (!memberName || !m || !ts.isMethodSignature(req))
412
437
  continue;
413
438
  if (!ts.isMethodDeclaration(m))
414
439
  return false;
@@ -432,9 +457,9 @@ export const componentMethods = {
432
457
  this.erasedSignatureMethods.add(m);
433
458
  }
434
459
  const args = req.parameters.map((p, k) => (ts.isIdentifier(p.name) ? ident(p.name.text) : `__p${k}`));
435
- const call = `${ident(name)}(${args.map((a, k) => (have[k] === want[k] ? a : erased(have[k], k) ? `${RT.jsUnchecked}<${have[k]}>(${a})` : `${a} as Any?`)).join(', ')})`;
436
- added.push(` override fun ${ident(name)}(${want.map((t, k) => `${args[k]}: ${t}`).join(', ')})${ret === 'Unit' ? '' : `: ${ret}`} { ${ret === 'Unit' ? call : ownRet === 'Unit' ? `${call}; return null` : `return ${call}`} }`);
437
- skipped.push(name);
460
+ const call = `${ident(memberName)}(${args.map((a, k) => (have[k] === want[k] ? a : erased(have[k], k) ? `${RT.jsUnchecked}<${have[k]}>(${a})` : `${a} as Any?`)).join(', ')})`;
461
+ added.push(` override fun ${ident(memberName)}(${want.map((t, k) => `${args[k]}: ${t}`).join(', ')})${ret === 'Unit' ? '' : `: ${ret}`} { ${ret === 'Unit' ? call : ownRet === 'Unit' ? `${call}; return null` : `return ${call}`} }`);
462
+ skipped.push(memberName);
438
463
  }
439
464
  out.push(...added);
440
465
  for (const n of skipped)
@@ -7,6 +7,7 @@ import { isKit, isUntyped, parseNativeType, spelledType } from "../semantics/typ
7
7
  import { hasModifier, isLibDeclaration } from "../semantics/ast.js";
8
8
  import { isPromiseType } from "../semantics/spelled.js";
9
9
  import { constClassExpr, constructorOf, spellInstantiatedCollection } from "../semantics/classes.js";
10
+ import { resolveWorkerScript } from "../semantics/worker-state.js";
10
11
  export const constructionMethods = {
11
12
  /** `new RegExp(…)`: from a pattern, or a copy of an expression with its flags unless others are given. */
12
13
  regExpConstruct(args, call = false) {
@@ -28,11 +29,9 @@ export const constructionMethods = {
28
29
  const clsExpr = constClassExpr(callee, this.checker);
29
30
  if (clsExpr)
30
31
  return `${this.emitClassExprCode(clsExpr)}(${this.args(e).join(', ')})`;
31
- if (name === 'Worker' && this.workerScripts && args.length) {
32
- const script = this.workerScript(args[0]);
33
- if (script)
34
- return `JSWorker(${this.coerce(args[0], 'Any?')}, ${kotlinString(script)})`;
35
- }
32
+ const workerScript = resolveWorkerScript(name, args, this.workerScripts, this.resolveAlias, 'android');
33
+ if (workerScript)
34
+ return `JSWorker(${this.coerce(args[0], 'Any?')}, ${kotlinString(workerScript)})`;
36
35
  if (BUFFER_TYPES.has(name) && this.resolve(callee)?.declarations?.every((d) => d.getSourceFile().isDeclarationFile))
37
36
  return this.newBuffer(name, args);
38
37
  const own = ts.isIdentifier(callee) ? this.resolve(callee)?.valueDeclaration : undefined;
@@ -4,7 +4,7 @@ import ts from 'typescript';
4
4
  import { accessorKey, cast, EMPTY_READ, functionTypeParts, ident, isNullable, kotlinString, lambda, optionalType, safeCast, splitTopLevel, RT } from "./syntax.js";
5
5
  import { UNKEYED, holdsNil, inPlanOrder, madeBitIn, memberKeysOf, memberOf, shapePlanOfShape, spelledOptional, resultShapeNamed } from "../semantics/shapes.js";
6
6
  import { codeStoreSlot, placeCode } from "../semantics/placement.js";
7
- import { heldOf, isUntyped, parseNativeType, spelledType } from "../semantics/types.js";
7
+ import { heldOf, isKit, isUntyped, parseNativeType, spelledType } from "../semantics/types.js";
8
8
  import { observers } from "../semantics/observers.js";
9
9
  import { abstractField, overAbstractOnly } from "../semantics/classes.js";
10
10
  export const conversionMethods = {
@@ -280,7 +280,12 @@ export const conversionMethods = {
280
280
  const ownNames = new Set([...this.instanceKeys()].map((d) => d.name.getText()));
281
281
  // A method read by name is a script function calling it with the arguments it is given.
282
282
  const method = (m) => {
283
- const args = m.params.map((t, k) => (m.unread?.[k] && this.zero(t)) || this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${k})`), t, true));
283
+ const args = m.params.map((t, k) => {
284
+ if (m.unread?.[k] && this.zero(t))
285
+ return this.zero(t);
286
+ const read = this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${k})`), t, true);
287
+ return m.defaults?.[k] ? `(if (__a.getOrNull(${k}) == null) ${m.defaults[k]} else ${read})` : read;
288
+ });
284
289
  // An app class's method sees the object it is called on as `this` when that is one of the class's (`obj[k].call(other)`).
285
290
  const call = `${receiver && !m.key ? `${RT.jsMethodReceiver}(__s, this, ${receiver}::class.java)` : 'this'}.${this.methodIdent(m.name)}(${args.join(', ')})`;
286
291
  const fn = receiver && !m.key ? `JSMethod(${m.params.length}) ${lambda(['__s', '__a'], m.ret === 'Unit' ? `${call}; null` : call)}` : `${RT.jsFunction} ${lambda(['__a'], m.ret === 'Unit' ? `${call}; null` : call)}`;
@@ -380,7 +385,7 @@ export const conversionMethods = {
380
385
  // App code: an untyped string or boolean is converted as JavaScript converts it where it is used, never refused.
381
386
  if (orZero && (type === 'String' || type === 'Boolean'))
382
387
  return this.fromAny(code, type);
383
- if (orZero && zero && zero !== 'null' && !type.endsWith('?'))
388
+ if (orZero && zero && zero !== 'null' && !type.endsWith('?') && !isKit(spelledType(type), 'JSNullish'))
384
389
  return `(${safeCast(code, type)} ?: ${zero})`;
385
390
  return this.fromAny(code, type);
386
391
  },
@@ -433,6 +438,9 @@ export const conversionMethods = {
433
438
  return read(code);
434
439
  return this.marks.isPure(code) ? `(if (${RT.jsIsNullish}(${code})) null else ${read(code)})` : `${RT.jsUnlessNullish}(${code}) { ${read('it')} }`;
435
440
  }
441
+ if (!this.library && (type === 'JSWorker' || type === 'JSWorker?')) {
442
+ return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}) { JSWorker.fromAny(it) }` : `JSWorker.fromAny(${code})`;
443
+ }
436
444
  if (!this.library && /^[A-Z]\w*\??$/.test(type)) {
437
445
  const reified = this.reifiedRead(code, type);
438
446
  if (reified)
@@ -443,6 +451,14 @@ export const conversionMethods = {
443
451
  if (fn && fn.params.length <= 7) {
444
452
  // Where the signatures do not settle it, a wrapper is read back as its own function (`, false`).
445
453
  const kind = /^JSArray</.test(fn.params.at(-1) ?? '') && fn.params.length <= 3 ? (this.restFunctionTypes.get(type.replace(/^\((.*)\)\?$/, '$1')) ?? 'both') : 'array';
454
+ const promiseRet = !this.library ? /^JSPromise<(.+)>$/.exec(fn.ret) : null;
455
+ if (promiseRet && !isUntyped(spelledType(promiseRet[1]))) {
456
+ const rawTyped = `${kind === 'array' ? 'jsFunction' : 'jsRestFunction'}${fn.params.length}<${[...fn.params, 'Any?'].join(', ')}>`;
457
+ const names = fn.params.map((_, k) => this.marks.pureCode(`__p${k}`));
458
+ const invoke = `${rawTyped}(__f${kind === 'both' ? ', false' : ''})(${names.join(', ')})`;
459
+ const wrap = (x) => `${x}.let { __f -> { ${fn.params.map((p, k) => `${names[k]}: ${p}`).join(', ')}${fn.params.length ? ' -> ' : ''}${this.fromAny(invoke, fn.ret)} } }`;
460
+ return /\)\?$/.test(type) ? `${RT.jsUnlessNullish}(${code}) { ${wrap('it')} }` : wrap(code);
461
+ }
446
462
  const typed = `${kind === 'array' ? 'jsFunction' : 'jsRestFunction'}${fn.params.length}<${[...fn.params, fn.ret].join(', ')}>`;
447
463
  const call = (x) => `${typed}(${x}${kind === 'both' ? ', false' : ''})`;
448
464
  return /\)\?$/.test(type) ? `${RT.jsUnlessNullish}(${code}) { ${call('it')} }` : call(code);
@@ -4,10 +4,11 @@ import { join } from 'node:path';
4
4
  import { addedDeclarations, augmentedProperty, isCoreDeclaration, ownPropertyOnly } from "../program/core-facts.js";
5
5
  import { KitTypes, coreClass, kitExtends, kitMember } from "../kit/kit-index.js";
6
6
  import { KIT_NAMES_ANDROID } from "./library.js";
7
- import { functionTypeParts, kotlinString, numberLiteral, splitTopLevel, RT } from "./syntax.js";
7
+ import { functionTypeParts, kotlinString, numberLiteral, safeCast, splitTopLevel, RT } from "./syntax.js";
8
8
  import { KIT_ANDROID } from "../driver/paths.js";
9
9
  import { rethrowUnlessRefused } from "../semantics/refusals.js";
10
10
  import { isMixinOwnMember } from "../semantics/classes.js";
11
+ import { nullableTypeNode } from "../semantics/lang.js";
11
12
  import { isUntyped, spelledType } from "../semantics/types.js";
12
13
  import { kotlinKitIndex, TOP_LEVEL, NATIVE_MEMBERS, SCRIPT_OBJECTS, KIT } from "./core-index.js";
13
14
  /** The native class a core view's `android` is. */
@@ -59,7 +60,7 @@ export class CoreKotlin extends KitTypes {
59
60
  if (!m || m.kind !== (ts.isCallExpression(x) ? 'func' : 'var'))
60
61
  return false;
61
62
  const k = m.type.trim();
62
- return k.endsWith('?') && !isUntyped(spelledType(k)) && !functionTypeParts(k.replace(/^\((.*)\)\?$/, '$1'));
63
+ return k.endsWith('?') && (!isUntyped(spelledType(k)) || !isUntyped(spelledType(this.t.typeOf(x)))) && !functionTypeParts(k.replace(/^\((.*)\)\?$/, '$1'));
63
64
  }
64
65
  catch (e) {
65
66
  rethrowUnlessRefused(e);
@@ -383,12 +384,29 @@ export class CoreKotlin extends KitTypes {
383
384
  const ps = Array.from({ length: arity }, (_, k) => `__s${k}`);
384
385
  return `{ ${ps.map((p) => `${p}: Any?`).join(', ')} -> ${recv}.${name}(${ps.join(', ')}) }`;
385
386
  }
387
+ // A kit method with non-null Kotlin default parameters (e.g. `flags: Double = 2.0`) where TS types the parameter optional (`Double?`):
388
+ // a method reference drops the default and keeps non-null `Double`, so wrap in a lambda that forwards the default.
389
+ const parsedParams = (m.params ?? '').trim()
390
+ ? splitTopLevel(m.params).map((p) => {
391
+ const hit = /^([^:]+):\s*(.+?)(?:\s*=\s*(.+))?$/.exec(p.trim());
392
+ return hit ? { type: hit[2].trim(), def: hit[3]?.trim() } : null;
393
+ })
394
+ : [];
395
+ const tsParts = functionTypeParts(t.typeOf(e).replace(/^\((.*)\)\?$/, '$1'));
396
+ if (tsParts && parsedParams.length === tsParts.params.length && parsedParams.every(Boolean) && parsedParams.some((p, k) => p.def && !p.type.endsWith('?') && tsParts.params[k].endsWith('?'))) {
397
+ const ps = tsParts.params.map((pt, k) => `__p${k}: ${pt}`);
398
+ const callArgs = parsedParams.map((p, k) => (p.def && !p.type.endsWith('?') && tsParts.params[k].endsWith('?') ? `(__p${k} ?: ${p.def})` : `__p${k}`));
399
+ const call = (r) => `{ ${ps.join(', ')} -> ${r}.${name}(${callArgs.join(', ')}) }`;
400
+ if (owner.isStatic)
401
+ return call(recv);
402
+ return recv.endsWith('?') ? `${recv.slice(0, -1)}?.let { __r -> ${call('__r')} }` : `(${recv}).let { __r -> ${call('__r')} }`;
403
+ }
386
404
  // A Kotlin object's own function is referenced on the object; a class's static, on its companion.
387
405
  if (owner.isStatic)
388
406
  return this.index.get(owner.name)?.object ? `${recv}::${name}` : `${recv}.Companion::${name}`;
389
407
  return recv.endsWith('?') ? `${recv.slice(0, -1)}?.let { __r -> __r::${name} }` : `${recv}::${name}`;
390
408
  }
391
- return this.fromKit(`${recv}.${name}`, m.type, t.typeOf(e), t.nullTolerant(e) || t.states.nilKept(e));
409
+ return this.fromKit(`${recv}.${name}`, m.type, t.typeOf(e), t.nullTolerant(e) || t.states.nilKept(e) || keepsNullable(e));
392
410
  }
393
411
  /** A core-typed receiver's code: unwrapped where it is nullable and the access is not an optional one (code checked without strictNullChecks). */
394
412
  receiver(target, access) {
@@ -507,7 +525,7 @@ export class CoreKotlin extends KitTypes {
507
525
  }
508
526
  // A function held in a field the kit declares nullable (`CssAnimationProperty.register`): present where it is called.
509
527
  const callee = held && /\)\?$/.test(m.type.trim()) ? `(${recv}.${name} ?: ${RT.jsNotAFunction}(${kotlinString(e.expression.getText().replace(/\s+/g, ''))}))` : `${recv}.${name}`;
510
- return this.fromKit(`${callee}(${args.join(', ')})`, m.type, t.typeOf(e), keepsNullable(e) || t.states.nilKept(e));
528
+ return this.fromKit(`${callee}(${args.join(', ')})`, m.type, t.typeOf(e), keepsNullable(e) || t.states.nilKept(e) || t.nullOk.has(e));
511
529
  }
512
530
  construct(e) {
513
531
  const resolved = this.t.resolve(e.expression);
@@ -720,7 +738,7 @@ export class CoreKotlin extends KitTypes {
720
738
  if (/^JSArray<.*>$/.test(kb) && /^JSArray<.*>$/.test(tb) && kb !== tb)
721
739
  return this.t.unchecked(tsType, code);
722
740
  if (kb !== tb && this.index.has(tb) && (kb === 'Any' || kitExtends(this.index, tb, kb)))
723
- return `(${code} as ${tb}${k.endsWith('?') && (tsType.endsWith('?') || keepNull) ? '?' : ''})`;
741
+ return k.endsWith('?') && (tsType.endsWith('?') || keepNull) ? safeCast(code, tb) : `(${code} as ${tb})`;
724
742
  if (k.endsWith('?') && !tsType.endsWith('?') && !isUntyped(spelledType(tsType))) {
725
743
  const zero = tsType === 'String' ? '""' : tsType === 'Double' ? '0.0' : tsType === 'Boolean' ? 'false' : null;
726
744
  return zero ? (heldLoss('kitResult', zero, { native: !!this.t.native }), `(${code} ?: ${zero})`) : keepNull ? code : this.t.asserted(code);
@@ -733,13 +751,19 @@ export class CoreKotlin extends KitTypes {
733
751
  return conversions[k] ? `(${code}).${conversions[k]}()` : code;
734
752
  }
735
753
  }
736
- /** Whether `e`'s value is only tested (a condition, the operand of `!`) or dropped. */
754
+ /** Whether `e`'s value is only tested (a condition, the operand of `!`), asserted nullable, optional-chained, coalesced, or dropped. */
737
755
  function keepsNullable(e) {
738
756
  let n = e;
739
757
  while (ts.isParenthesizedExpression(n.parent))
740
758
  n = n.parent;
741
759
  const p = n.parent;
742
- return ts.isExpressionStatement(p) || (ts.isConditionalExpression(p) && p.condition === n) || (ts.isIfStatement(p) && p.expression === n) || (ts.isPrefixUnaryExpression(p) && p.operator === ts.SyntaxKind.ExclamationToken);
760
+ return (ts.isExpressionStatement(p) ||
761
+ ((ts.isAsExpression(p) || ts.isTypeAssertionExpression(p)) && nullableTypeNode(p.type)) ||
762
+ (ts.isConditionalExpression(p) && p.condition === n) ||
763
+ (ts.isIfStatement(p) && p.expression === n) ||
764
+ (ts.isPrefixUnaryExpression(p) && p.operator === ts.SyntaxKind.ExclamationToken) ||
765
+ (ts.isBinaryExpression(p) && p.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken && p.left === n) ||
766
+ ((ts.isPropertyAccessExpression(p) || ts.isElementAccessExpression(p) || ts.isCallExpression(p)) && p.expression === n && !!p.questionDotToken));
743
767
  }
744
768
  /**
745
769
  * What kit-android's build compiles: the generated code, src/fromcore, src/main (the runtime and the hand-written files
@@ -149,7 +149,7 @@ export const declarationsMethods = {
149
149
  }
150
150
  // A literal first value nothing reads (`let fps = 0` set again before any read) is left out.
151
151
  const deadLiteral = !!d.initializer && !constant && isConstant(d.initializer) && !this.pluginFiles.has(d.getSourceFile().fileName);
152
- const set = (!d.initializer || deadLiteral) && !lowered ? this.assignedBeforeUse(d) : null;
152
+ const set = (!d.initializer || deadLiteral) && !lowered && !this.asyncCtx ? this.assignedBeforeUse(d) : null;
153
153
  if (set)
154
154
  return `${i}${set === 'once' ? 'val' : 'var'} ${name}: ${t}`;
155
155
  // Lenient code may read it before any assignment (`let found: boolean; … typeof found`): undefined until assigned.
@@ -455,8 +455,13 @@ export const declarationsMethods = {
455
455
  // A match reads its values as an array does.
456
456
  const js = ts.isArrayBindingPattern(name) && !/^JSMatch\??$/.test(this.typeOf(init)) ? this.patternIteration(init) : null;
457
457
  // A literal builds a shape class of its own, which the pattern's contextual shape need not be.
458
- if (!js)
459
- return ts.isObjectLiteralExpression(init) ? ` = ${this.expr(init)}` : `: ${this.typeOf(init)} = ${this.coerce(init, this.typeOf(init))}`;
458
+ if (!js) {
459
+ if (ts.isObjectLiteralExpression(init))
460
+ return ` = ${this.expr(init)}`;
461
+ const t = this.typeOf(init);
462
+ const target = isNullable(t) && !isUntyped(spelledType(t)) ? t.slice(0, -1) : t;
463
+ return `: ${target} = ${this.coerce(init, target)}`;
464
+ }
460
465
  const rest = name.elements.some((el) => ts.isBindingElement(el) && el.dotDotDotToken);
461
466
  return ` = JSArray(ArrayList(${js}.${rest ? 'jsCollect()' : `jsTake(${name.elements.length})`}))`;
462
467
  },
@@ -5,7 +5,7 @@ import { propertyKeyCode, templateSubstitution } from "../semantics/apis/operato
5
5
  import { BUFFER_TYPES } from "../semantics/globals.js";
6
6
  import { branch, cast, escapeText, functionTypeParts, ident, isFunctionType, isNullable, kotlinString, numberLiteral, optionalType, safeCast, RT, assertedReader } from "./syntax.js";
7
7
  import { awaitedCell, isEnumObject, nullishField } from "../semantics/placement.js";
8
- import { globalProxyUse, isStringRaw, readWrite, statementLevel, templateParts } from "../semantics/lang.js";
8
+ import { globalProxyUse, isStringRaw, nullableTypeNode, readWrite, statementLevel, templateParts } from "../semantics/lang.js";
9
9
  import { readKeyOf } from "../semantics/nullish.js";
10
10
  import { convertedRead, onlyNull } from "../semantics/states/predicates.js";
11
11
  import { isLibDeclaration, isWriteTarget } from "../semantics/ast.js";
@@ -116,8 +116,9 @@ export const expressionsMethods = {
116
116
  let last = e.right;
117
117
  while (ts.isBinaryExpression(last) && last.operatorToken.kind === ts.SyntaxKind.EqualsToken)
118
118
  last = last.right;
119
+ const target = (this.declaredTypeOf(e.left) ?? this.typeOf(e.left)).replace(/\?$/, '');
119
120
  // A literal stored into a typed target is made as that target's shape.
120
- const shaped = !this.library && ts.isObjectLiteralExpression(last) && ts.isIdentifier(e.left) && !isUntyped(spelledType(this.declaredTypeOf(e.left) ?? 'Any?')) ? this.declaredTypeOf(e.left) : null;
121
+ const shaped = !this.library && ts.isObjectLiteralExpression(last) && !isUntyped(spelledType(target)) && target !== 'Unit' && !isKit(spelledType(target), 'JSObject') ? (ts.isIdentifier(e.left) ? (this.declaredTypeOf(e.left) ?? target) : target) : null;
121
122
  let t = shaped ?? (this.typeOf(e.right) === 'Unit' || (!this.library && ts.isObjectLiteralExpression(last)) ? 'Any?' : this.typeOf(e.right));
122
123
  // `a = b = null`: null of the target's type.
123
124
  const unset = e.right.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(e.right) && e.right.text === 'undefined');
@@ -139,7 +140,6 @@ export const expressionsMethods = {
139
140
  if (this.library && this.isObjectType(t) && this.declaredTypeOf(e.left) === optionalType(t) && this.nullTolerant(e))
140
141
  t = optionalType(t);
141
142
  // `(map[k] = [])`: TypeScript types the empty literal `never[]`; it is made as the target's array, the one stored.
142
- const target = (this.declaredTypeOf(e.left) ?? this.typeOf(e.left)).replace(/\?$/, '');
143
143
  if (ts.isArrayLiteralExpression(last) && !last.elements.length && t === 'JSArray<Any?>' && isKit(spelledType(target), 'JSArray'))
144
144
  t = target;
145
145
  const v = this.fresh('__assigned');
@@ -261,13 +261,18 @@ export const expressionsMethods = {
261
261
  return from.endsWith('?') ? `${this.expr(e.expression)}?.let { ${this.viewOf(toName, 'it')} }` : this.viewOf(toName, this.expr(e.expression));
262
262
  }
263
263
  if (from !== to && from.replace(/\?$/, '') !== to.replace(/\?$/, '') && this.isObjectRef(e) && this.isObjectRef(e.expression)) {
264
+ // A nullable type assertion (`x as View | undefined`, `x as View | null`): safe cast (`as?`), returning null for null or another class.
265
+ if (isNullable(to))
266
+ return safeCast(this.expr(e.expression), to.replace(/\?$/, ''));
267
+ if (!this.library && !ts.isSatisfiesExpression(e) && nullableTypeNode(e.type) && (this.nullOk.has(e) || this.nullTolerant(e) || ts.isOptionalChain(ts.walkUpParenthesizedExpressions(e.parent))))
268
+ return safeCast(this.expr(e.expression), to);
264
269
  // Library mode: a script assertion never fails, so a value of another class (a TabViewItem walked up to as a parent)
265
270
  // or a null Java result (`dlg.findViewById(id) as TextView`) reads as null instead of throwing ClassCastException/NPE.
266
- if (this.library && this.isClassDowncast(e) && (isNullable(to) || this.functionLiteralArgument(e)))
271
+ if (this.library && this.isClassDowncast(e) && this.functionLiteralArgument(e))
267
272
  return safeCast(this.expr(e.expression), to.replace(/\?$/, ''));
268
273
  if (this.library && this.native?.type(this.checker.getNonNullableType(this.checker.getTypeAtLocation(e))) && this.native?.type(this.checker.getNonNullableType(this.checker.getTypeAtLocation(e.expression)))) {
269
274
  const safe = safeCast(this.expr(e.expression), to.replace(/\?$/, ''));
270
- return isNullable(to) || this.nullOk.has(e) ? safe : this.unchecked(to, safe);
275
+ return this.nullOk.has(e) ? safe : this.unchecked(to, safe);
271
276
  }
272
277
  return this.classCast(this.expr(e.expression), from, to);
273
278
  }
@@ -1,7 +1,7 @@
1
- import { SHARED_LIB_CONSTANTS } from "../semantics/globals.js";
1
+ import { BUFFER_TYPES, SHARED_LIB_CONSTANTS } from "../semantics/globals.js";
2
2
  import { RT } from "./syntax.js";
3
3
  // No prototype: a name like `toString` is no error class.
4
- export const BUILTIN_CLASSES = Object.assign(Object.create(null), { Promise: 'JSPromise<*>', Array: 'JSArray<*>', Map: 'JSMap<*, *>', Set: 'JSSet<*>', Date: 'JSDate' });
4
+ export const BUILTIN_CLASSES = Object.assign(Object.create(null), { Promise: 'JSPromise<*>', Array: 'JSArray<*>', Map: 'JSMap<*, *>', Set: 'JSSet<*>', Date: 'JSDate', RegExp: 'JSRegExp' }, Object.fromEntries([...BUFFER_TYPES].map((n) => [n, `JS${n}`])));
5
5
  /** Core classes kit-android implements under another name. */
6
6
  export const KIT_NAMES_ANDROID = { ViewBase: 'View', ViewCommon: 'View', EditableTextBase: 'TextBase', LayoutBaseCommon: 'LayoutBase' };
7
7
  /** `Math`'s functions, as Kotlin calls them. */
@@ -712,12 +712,16 @@ export const modulesMethods = {
712
712
  return { name: m.name.text, type: m.questionToken ? optionalType(t) : t, readonly: hasModifier(m, ts.SyntaxKind.ReadonlyKeyword) };
713
713
  });
714
714
  const methods = members.filter(ts.isMethodSignature).map((m) => {
715
- const params = m.parameters.map((p, k) => ({ name: ts.isIdentifier(p.name) ? ident(p.name.text) : `p${k}`, type: this.requirementParamType(p), undefinedDefault: !!p.questionToken && this.states.nullishHeld(p) }));
715
+ const params = m.parameters.map((p, k) => {
716
+ const type = this.requirementParamType(p);
717
+ const defaultVal = p.questionToken ? (this.states.nullishHeld(p) ? ' = JSNullish.Undefined' : isNullable(type) || isUntyped(spelledType(type)) ? ' = null' : '') : '';
718
+ return { name: ts.isIdentifier(p.name) ? ident(p.name.text) : `p${k}`, type, defaultVal };
719
+ });
716
720
  const methodName = protocolMethodName(m.name, this.checker, ident);
717
721
  return { name: methodName, key: m.name.getText(), params, ret: this.returnTypeOf(m) };
718
722
  });
719
- // The interface's own declaration gives an omitted `JSNullish` argument its undefined; overrides inherit it.
720
- const signature = (m, declared = false) => `fun ${m.name}(${m.params.map((p) => `${p.name}: ${p.type}${declared && p.undefinedDefault ? ' = JSNullish.Undefined' : ''}`).join(', ')})${m.ret === 'Unit' ? '' : `: ${m.ret}`}`;
723
+ // The interface's own declaration gives an omitted optional argument its default; overrides inherit it.
724
+ const signature = (m, declared = false) => `fun ${m.name}(${m.params.map((p) => `${p.name}: ${p.type}${declared ? p.defaultVal : ''}`).join(', ')})${m.ret === 'Unit' ? '' : `: ${m.ret}`}`;
721
725
  const fnType = (m) => `(${m.params.map((p) => p.type).join(', ')}) -> ${m.ret}`;
722
726
  const lines = [`interface ${name} : JSDynamic {`];
723
727
  // Library mode: read-only in the interface, so a class implementing it may hold a narrower type (`android: MotionEvent` for `any`).
@@ -740,10 +744,11 @@ export const modulesMethods = {
740
744
  interfacesOf(file) {
741
745
  let out = '';
742
746
  const emitted = new Set();
747
+ const norm = file.replace(/\\/g, '/');
743
748
  for (let more = true; more;) {
744
749
  more = false;
745
750
  for (const [name, decl] of this.interfaces) {
746
- if (decl.file !== file || emitted.has(name) || !this.used.has(name))
751
+ if (decl.file.replace(/\\/g, '/') !== norm || emitted.has(name) || !this.used.has(name))
747
752
  continue;
748
753
  out = decl.code() + '\n\n' + out;
749
754
  emitted.add(name);
@@ -201,8 +201,11 @@ export const namesMethods = {
201
201
  // A function taking `this` as a value (a property descriptor's `set`): the receiver is the caller's.
202
202
  if (self || this.implicitThis(fnDecl)) {
203
203
  const thisType = self ? this.type(this.checker.getTypeAtLocation(self.name), self) : 'Any?';
204
- const args = this.readsArguments(fnDecl) ? ['JSArray(__a.toMutableList())'] : fnDecl.parameters.filter((q) => !isThisParameter(q)).map((q, k) => (q.dotDotDotToken ? `JSArray(__a.drop(${k}).map { ${this.fromAnyCode('it', this.typeOf(q.name).replace(/^JSArray<(.*)>$/, '$1'), true)} }.toMutableList())` : this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${k})`), this.paramType(q), true)));
205
- return `JSMethod ${lambda(['__self', '__a'], `${ref}(${[isUntyped(spelledType(thisType)) ? '__self' : this.fromAnyCode('__self', thisType, true), ...args].join(', ')})`)}`;
204
+ const params = fnDecl.parameters.filter((q) => !isThisParameter(q));
205
+ const arity = params.findIndex((q) => !!q.questionToken || !!q.initializer || !!q.dotDotDotToken);
206
+ const len = arity < 0 ? params.length : arity;
207
+ const args = this.readsArguments(fnDecl) ? ['JSArray(__a.toMutableList())'] : params.map((q, k) => (q.dotDotDotToken ? `JSArray(__a.drop(${k}).map { ${this.fromAnyCode('it', this.typeOf(q.name).replace(/^JSArray<(.*)>$/, '$1'), true)} }.toMutableList())` : this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${k})`), this.paramType(q), true)));
208
+ return `JSMethod(${len}) ${lambda(['__self', '__a'], `${ref}(${[isUntyped(spelledType(thisType)) ? '__self' : this.fromAnyCode('__self', thisType, true), ...args].join(', ')})`)}`;
206
209
  }
207
210
  // Library mode: a function of an optional string, number or boolean held as a value (a shorthand's converter) may be given
208
211
  // anything (core probes converters with `unsetValue`): another kind of value is none of them, as `typeof` finds it.
@@ -43,7 +43,8 @@ export const narrowingMethods = {
43
43
  const keyed = (actual === 'Double' || actual === 'String') && this.states.unsetNullField(e) ? this.states.nullableEntry(e, () => this.expr(e)) : null;
44
44
  if (keyed)
45
45
  return () => `${actual === 'Double' ? RT.jsToNumber : RT.jsToString}(${keyed})`;
46
- if (['String', 'Double', 'Boolean'].includes(actual) && this.states.nilIsNull(e))
46
+ const nullishDefault = !!sym?.valueDeclaration && ts.isParameter(sym.valueDeclaration) && !!sym.valueDeclaration.initializer && this.states.nullishHeld(sym.valueDeclaration);
47
+ if (['String', 'Double', 'Boolean'].includes(actual) && (this.states.nilIsNull(e) || nullishDefault))
47
48
  return (code) => nullAs(code, actual);
48
49
  if (this.lenient || ['String', 'Double', 'Boolean'].includes(actual))
49
50
  return (code) => this.undefinedAs(code, actual);