@nstudio/nativescript-compiler 9.2.0-alpha.14 → 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.
- package/dist/driver/compile.js +4 -3
- package/dist/kotlin/arguments.js +2 -1
- package/dist/kotlin/builtins.js +14 -3
- package/dist/kotlin/class-constructor.js +3 -1
- package/dist/kotlin/class-methods.js +9 -2
- package/dist/kotlin/components.js +39 -14
- package/dist/kotlin/construction.js +4 -5
- package/dist/kotlin/conversion.js +16 -3
- package/dist/kotlin/core-api.js +14 -7
- package/dist/kotlin/declarations.js +1 -1
- package/dist/kotlin/expressions.js +10 -5
- package/dist/kotlin/modules.js +7 -3
- package/dist/kotlin/names.js +5 -2
- package/dist/kotlin/optional-chains.js +24 -5
- package/dist/kotlin/overrides.js +7 -2
- package/dist/kotlin/placement.js +5 -4
- package/dist/kotlin/translator.js +0 -39
- package/dist/kotlin/types.js +4 -5
- package/dist/kotlin/untyped-values.js +7 -1
- package/dist/program/program.js +3 -3
- package/dist/semantics/apis/array.js +11 -0
- package/dist/semantics/classes.js +24 -0
- package/dist/semantics/config.js +2 -0
- package/dist/semantics/forms/by-name.js +30 -18
- package/dist/semantics/globals.js +8 -2
- package/dist/semantics/lang.js +4 -0
- package/dist/semantics/ledger.js +0 -24
- package/dist/semantics/platform-globals.js +0 -16
- package/dist/semantics/refusals.js +1 -1
- package/dist/semantics/runtime.js +2 -0
- package/dist/semantics/throws.js +7 -0
- package/dist/semantics/worker-state.js +41 -1
- package/dist/swift/assignment.js +3 -0
- package/dist/swift/builtins.js +8 -10
- package/dist/swift/class-methods.js +3 -1
- package/dist/swift/construction.js +5 -1
- package/dist/swift/conversion.js +1 -1
- package/dist/swift/expressions.js +2 -4
- package/dist/swift/from-any.js +5 -0
- package/dist/swift/global-calls.js +8 -1
- package/dist/swift/object-classes.js +2 -1
- package/dist/swift/protocols.js +5 -16
- package/dist/swift/types.js +4 -3
- package/dist/targets/ios/build.js +22 -7
- package/docs/cli/compile-ios.md +1 -1
- package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +6 -6
- package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -1
- package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Collections.kt +15 -6
- package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Promise.kt +1 -1
- package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +13 -2
- package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +0 -12
- package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -39
- package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +0 -44
- package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +19 -2
- package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +87 -22
- package/kit-apple/Sources/NativeScriptKit/Core/text.text-common.swift +9 -1
- package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +13 -2
- package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +26 -2
- package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.liquid-glass-container.index.ios.swift +12 -2
- package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.root-layout.root-layout-common.swift +46 -6
- package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +37 -3
- package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.split-view-common.swift +12 -1
- package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +50 -6
- package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.text-base-common.swift +13 -1
- package/kit-apple/Sources/NativeScriptKit/Runtime/Collections.swift +5 -1
- package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +13 -2
- package/kit-apple/Sources/NativeScriptKit/Runtime/Errors.swift +10 -2
- package/kit-apple/Sources/NativeScriptKit/Runtime/Functions.swift +57 -12
- package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +12 -3
- package/kit-apple/Sources/NativeScriptKit/Runtime/Promise.swift +56 -29
- package/kit-apple/Sources/NativeScriptKit/Runtime/Realm.swift +92 -0
- package/kit-apple/Sources/NativeScriptKit/Runtime/Record.swift +25 -5
- package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +13 -4
- package/kit-apple/Sources/NativeScriptKit/Runtime/RegExpEngine.swift +14 -5
- package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +28 -6
- package/kit-apple/Sources/NativeScriptKit/Runtime/Threads.swift +2 -2
- package/kit-apple/Sources/NativeScriptKit/Runtime/Timers.swift +93 -47
- package/kit-apple/Sources/NativeScriptKit/Runtime/TypedArrays.swift +37 -9
- package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +6 -4
- package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +11 -2
- package/kit-apple/Sources/NativeScriptKit/Runtime/Workers.swift +680 -0
- package/package.json +1 -1
package/dist/driver/compile.js
CHANGED
|
@@ -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
|
|
122
|
-
const leftOut = new Set(
|
|
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,
|
package/dist/kotlin/arguments.js
CHANGED
|
@@ -263,7 +263,8 @@ export const argumentsMethods = {
|
|
|
263
263
|
if (literal && (this.readsArguments(literal) || literal.parameters.some((q) => q.dotDotDotToken || isThisParameter(q) || !ts.isIdentifier(q.name))))
|
|
264
264
|
return null;
|
|
265
265
|
const sigs = this.checker.getTypeAtLocation(e).getNonNullableType().getCallSignatures();
|
|
266
|
-
|
|
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)))
|
|
267
268
|
return null;
|
|
268
269
|
const source = this.typeOf(e);
|
|
269
270
|
const parts = this.scriptReadParts(source);
|
package/dist/kotlin/builtins.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
@@ -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
|
|
403
|
-
const m =
|
|
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 (
|
|
406
|
-
const
|
|
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(
|
|
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 (
|
|
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(
|
|
436
|
-
added.push(` override fun ${ident(
|
|
437
|
-
skipped.push(
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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) =>
|
|
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
|
},
|
|
@@ -446,6 +451,14 @@ export const conversionMethods = {
|
|
|
446
451
|
if (fn && fn.params.length <= 7) {
|
|
447
452
|
// Where the signatures do not settle it, a wrapper is read back as its own function (`, false`).
|
|
448
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
|
+
}
|
|
449
462
|
const typed = `${kind === 'array' ? 'jsFunction' : 'jsRestFunction'}${fn.params.length}<${[...fn.params, fn.ret].join(', ')}>`;
|
|
450
463
|
const call = (x) => `${typed}(${x}${kind === 'both' ? ', false' : ''})`;
|
|
451
464
|
return /\)\?$/.test(type) ? `${RT.jsUnlessNullish}(${code}) { ${call('it')} }` : call(code);
|
package/dist/kotlin/core-api.js
CHANGED
|
@@ -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);
|
|
@@ -405,7 +406,7 @@ export class CoreKotlin extends KitTypes {
|
|
|
405
406
|
return this.index.get(owner.name)?.object ? `${recv}::${name}` : `${recv}.Companion::${name}`;
|
|
406
407
|
return recv.endsWith('?') ? `${recv.slice(0, -1)}?.let { __r -> __r::${name} }` : `${recv}::${name}`;
|
|
407
408
|
}
|
|
408
|
-
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));
|
|
409
410
|
}
|
|
410
411
|
/** A core-typed receiver's code: unwrapped where it is nullable and the access is not an optional one (code checked without strictNullChecks). */
|
|
411
412
|
receiver(target, access) {
|
|
@@ -524,7 +525,7 @@ export class CoreKotlin extends KitTypes {
|
|
|
524
525
|
}
|
|
525
526
|
// A function held in a field the kit declares nullable (`CssAnimationProperty.register`): present where it is called.
|
|
526
527
|
const callee = held && /\)\?$/.test(m.type.trim()) ? `(${recv}.${name} ?: ${RT.jsNotAFunction}(${kotlinString(e.expression.getText().replace(/\s+/g, ''))}))` : `${recv}.${name}`;
|
|
527
|
-
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));
|
|
528
529
|
}
|
|
529
530
|
construct(e) {
|
|
530
531
|
const resolved = this.t.resolve(e.expression);
|
|
@@ -737,7 +738,7 @@ export class CoreKotlin extends KitTypes {
|
|
|
737
738
|
if (/^JSArray<.*>$/.test(kb) && /^JSArray<.*>$/.test(tb) && kb !== tb)
|
|
738
739
|
return this.t.unchecked(tsType, code);
|
|
739
740
|
if (kb !== tb && this.index.has(tb) && (kb === 'Any' || kitExtends(this.index, tb, kb)))
|
|
740
|
-
return
|
|
741
|
+
return k.endsWith('?') && (tsType.endsWith('?') || keepNull) ? safeCast(code, tb) : `(${code} as ${tb})`;
|
|
741
742
|
if (k.endsWith('?') && !tsType.endsWith('?') && !isUntyped(spelledType(tsType))) {
|
|
742
743
|
const zero = tsType === 'String' ? '""' : tsType === 'Double' ? '0.0' : tsType === 'Boolean' ? 'false' : null;
|
|
743
744
|
return zero ? (heldLoss('kitResult', zero, { native: !!this.t.native }), `(${code} ?: ${zero})`) : keepNull ? code : this.t.asserted(code);
|
|
@@ -750,13 +751,19 @@ export class CoreKotlin extends KitTypes {
|
|
|
750
751
|
return conversions[k] ? `(${code}).${conversions[k]}()` : code;
|
|
751
752
|
}
|
|
752
753
|
}
|
|
753
|
-
/** 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. */
|
|
754
755
|
function keepsNullable(e) {
|
|
755
756
|
let n = e;
|
|
756
757
|
while (ts.isParenthesizedExpression(n.parent))
|
|
757
758
|
n = n.parent;
|
|
758
759
|
const p = n.parent;
|
|
759
|
-
return ts.isExpressionStatement(p) ||
|
|
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));
|
|
760
767
|
}
|
|
761
768
|
/**
|
|
762
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.
|
|
@@ -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) &&
|
|
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) &&
|
|
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
|
|
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
|
}
|
package/dist/kotlin/modules.js
CHANGED
|
@@ -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) =>
|
|
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
|
|
720
|
-
const signature = (m, declared = false) => `fun ${m.name}(${m.params.map((p) => `${p.name}: ${p.type}${declared
|
|
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`).
|
package/dist/kotlin/names.js
CHANGED
|
@@ -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
|
|
205
|
-
|
|
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.
|
|
@@ -4,7 +4,7 @@ import ts from 'typescript';
|
|
|
4
4
|
import { isLibGlobal } from "../semantics/globals.js";
|
|
5
5
|
import { cast, earlyBacking, ident, isFunctionType, isNullable, kotlinString, optionalType, safeCast, RT } from "./syntax.js";
|
|
6
6
|
import { elementReceiverCell, keyName, isEnumObject, receiverCell, receiverSlot } from "../semantics/placement.js";
|
|
7
|
-
import { uncheckedMatch } from "../semantics/lang.js";
|
|
7
|
+
import { nullableTypeNode, uncheckedMatch } from "../semantics/lang.js";
|
|
8
8
|
import { isLibDeclaration, isWriteTarget } from "../semantics/ast.js";
|
|
9
9
|
import { isKit, isNamed, isUntyped, parseNativeType, spelledType } from "../semantics/types.js";
|
|
10
10
|
export const optionalChainsMethods = {
|
|
@@ -12,10 +12,29 @@ export const optionalChainsMethods = {
|
|
|
12
12
|
while (ts.isParenthesizedExpression(e))
|
|
13
13
|
e = e.expression;
|
|
14
14
|
// `a ?? b` of objects where `b` may be missing too: missing then.
|
|
15
|
-
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken && !this.library && this.isObjectRef(e) && !isNullable(this.typeOf(e))
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken && !this.library && this.isObjectRef(e) && !isNullable(this.typeOf(e))) {
|
|
16
|
+
if (this.states.missingObject(e)) {
|
|
17
|
+
const code = this.expr(e);
|
|
18
|
+
if (this.isAsserted(code))
|
|
19
|
+
return this.unasserted(code);
|
|
20
|
+
}
|
|
21
|
+
const rightMaybe = this.maybeUndefined(e.right);
|
|
22
|
+
if (rightMaybe)
|
|
23
|
+
return `(${this.coerce(e.left, optionalType(this.typeOf(e)))} ?: ${rightMaybe})`;
|
|
24
|
+
}
|
|
25
|
+
// A kit method whose Kotlin signature returns nullable (`ViewBase.getViewById`: `ViewBase?`) though core's typings say present.
|
|
26
|
+
if (ts.isCallExpression(e) && !this.library && !this.nullOk.has(e) && !isNullable(this.typeOf(e)) && this.isObjectRef(e) && !isFunctionType(this.typeOf(e)) && this.core?.kitNil?.(e)) {
|
|
27
|
+
this.nullOk.add(e);
|
|
28
|
+
try {
|
|
29
|
+
return this.expr(e);
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
this.nullOk.delete(e);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// `x as T | undefined` / `x as T | null` where non-strictNullChecks stripped the union: safe cast returning nullable.
|
|
36
|
+
if ((ts.isAsExpression(e) || ts.isTypeAssertionExpression(e)) && !this.library && !isNullable(this.typeOf(e)) && this.isObjectRef(e) && this.isObjectRef(e.expression) && nullableTypeNode(e.type)) {
|
|
37
|
+
return safeCast(this.expr(e.expression), this.typeOf(e));
|
|
19
38
|
}
|
|
20
39
|
const assertion = this.assertedUntyped(e);
|
|
21
40
|
if (assertion)
|
package/dist/kotlin/overrides.js
CHANGED
|
@@ -151,6 +151,8 @@ export const overridesMethods = {
|
|
|
151
151
|
}
|
|
152
152
|
if (isUntyped(spelledType(from)))
|
|
153
153
|
return this.fromAny(code, to);
|
|
154
|
+
if (!this.library && from === 'JSPromise<Unit>' && /^JSPromise<(.+)>$/.test(to) && to !== from)
|
|
155
|
+
return this.fromAny(code, to);
|
|
154
156
|
if (to === optionalType(from))
|
|
155
157
|
return code;
|
|
156
158
|
// An array of one element type where another is declared (`string[]` given as `any[]`): convert structural elements, else share the array.
|
|
@@ -367,8 +369,11 @@ export const overridesMethods = {
|
|
|
367
369
|
return true;
|
|
368
370
|
for (const h of decl.heritageClauses ?? []) {
|
|
369
371
|
for (const x of h.types) {
|
|
370
|
-
if (
|
|
371
|
-
|
|
372
|
+
if (h.token === ts.SyntaxKind.ImplementsKeyword && this.implementedName(x) === name) {
|
|
373
|
+
const iface = this.checker.getTypeAtLocation(x).getSymbol()?.declarations?.find(ts.isInterfaceDeclaration);
|
|
374
|
+
if (this.protocolWitnesses(decl, iface, name, [], new Set()))
|
|
375
|
+
return true;
|
|
376
|
+
}
|
|
372
377
|
if (h.token === ts.SyntaxKind.ExtendsKeyword && this.declaresInterface(this.checker.getTypeAtLocation(x), name))
|
|
373
378
|
return true;
|
|
374
379
|
}
|
package/dist/kotlin/placement.js
CHANGED
|
@@ -470,7 +470,8 @@ export const placementMethods = {
|
|
|
470
470
|
const call = `${this.library ? this.refName(e) : ident(e.text)}(${names.map((n, k) => this.convert(n, g.params[k], f.params[k])).join(', ')})`;
|
|
471
471
|
return `{ ${g.params.map((p, k) => `${names[k]}: ${p}`).join(', ')} -> ${call} }`;
|
|
472
472
|
}
|
|
473
|
-
|
|
473
|
+
const voidPromiseRet = !this.library && !!f && !!g && f.ret === 'JSPromise<Unit>' && /^JSPromise<.+>$/.test(g.ret) && g.ret !== f.ret;
|
|
474
|
+
if (f && g && f.params.length <= g.params.length && (f.params.length < g.params.length || voidPromiseRet || f.params.some((p, k) => p !== g.params[k] && this.convert('x', g.params[k], p) !== 'x')) && (g.ret === 'Unit' || g.ret === f.ret || voidPromiseRet || (isUntyped(spelledType(g.ret)) && (this.library || f.ret !== 'Unit')) || (!this.library && isUntyped(spelledType(f.ret))))) {
|
|
474
475
|
const names = g.params.map((_, k) => this.marks.pureCode(`__a${k}`));
|
|
475
476
|
const fn = this.functionValue(e);
|
|
476
477
|
// A function field Kotlin declares nullable (one left unset): unwrapped where it is called.
|
|
@@ -479,8 +480,8 @@ export const placementMethods = {
|
|
|
479
480
|
.slice(0, f.params.length)
|
|
480
481
|
.map((n, k) => this.convert(n, g.params[k], f.params[k]))
|
|
481
482
|
.join(', ')})`;
|
|
482
|
-
// An untyped result is read as the slot's.
|
|
483
|
-
const call = isUntyped(spelledType(f.ret)) && g.ret !== 'Unit' && !isUntyped(spelledType(g.ret)) && !this.library ? this.fromAny(called, g.ret) : called;
|
|
483
|
+
// An untyped result (or Promise<void> into Promise<T | void>) is read as the slot's.
|
|
484
|
+
const call = voidPromiseRet || (isUntyped(spelledType(f.ret)) && g.ret !== 'Unit' && !isUntyped(spelledType(g.ret)) && !this.library) ? this.fromAny(called, g.ret) : called;
|
|
484
485
|
const adapter = `{ ${g.params.map((p, k) => `${names[k]}: ${p}`).join(', ')} -> ${call} }`;
|
|
485
486
|
// An optional member (`closeCallback?: …`) given to an optional parameter (`cb?: …`): undefined stays undefined,
|
|
486
487
|
// as the checker without strictNullChecks types neither as optional.
|
|
@@ -567,7 +568,7 @@ export const placementMethods = {
|
|
|
567
568
|
return elements(code);
|
|
568
569
|
}
|
|
569
570
|
}
|
|
570
|
-
if (!this.library && sb === 'JSPromise<Any?>' && /^JSPromise<(.+)>$/.test(tb))
|
|
571
|
+
if (!this.library && (sb === 'JSPromise<Any?>' || sb === 'JSPromise<Unit>') && /^JSPromise<(.+)>$/.test(tb) && tb !== sb)
|
|
571
572
|
return this.fromAny(this.functionValue(e), target);
|
|
572
573
|
if (head(sb) && head(sb) === head(tb) && sb !== tb)
|
|
573
574
|
return cast(this.functionValue(e), target);
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { dirname as pathDirname, resolve as pathResolve } from 'node:path';
|
|
2
1
|
import { heldLoss } from "../semantics/losses.js";
|
|
3
2
|
import ts from 'typescript';
|
|
4
3
|
import { KOTLIN_LEDGER } from "../semantics/ledger.js";
|
|
@@ -87,9 +86,6 @@ export class Translator {
|
|
|
87
86
|
nativeDeclared = (d) => !!this.native?.isNativeDeclaration(d);
|
|
88
87
|
/** The innermost statement or expression being translated: where code made from a type alone is placed. */
|
|
89
88
|
translating;
|
|
90
|
-
/** Android: the worker scripts compiled with the app, by file, and the name the entry registers each under. */
|
|
91
|
-
workerScripts;
|
|
92
|
-
resolveAlias;
|
|
93
89
|
/** The generated kit: a module's name for `AppModules.runImport`, set where modules `await import(…)` reaches run when imported. */
|
|
94
90
|
moduleKey;
|
|
95
91
|
/** The program's whole-program answers, shared with any translator of the same checker and files. */
|
|
@@ -148,8 +144,6 @@ export class Translator {
|
|
|
148
144
|
this.framework = new Framework(c.hooks);
|
|
149
145
|
this.checker = checker;
|
|
150
146
|
this.lenient = c.lenient ?? false;
|
|
151
|
-
this.workerScripts = c.workerScripts ?? null;
|
|
152
|
-
this.resolveAlias = c.resolveAlias ?? null;
|
|
153
147
|
this.moduleThread = c.moduleThread ?? null;
|
|
154
148
|
this.moduleKey = c.moduleKey;
|
|
155
149
|
this.components = components;
|
|
@@ -731,39 +725,6 @@ export class Translator {
|
|
|
731
725
|
});
|
|
732
726
|
return `object : ${this.className(base)}() {\n${members.join('\n')}\n}`;
|
|
733
727
|
}
|
|
734
|
-
/** `new Worker('~/x')`, `new Worker('./x')`, or `new Worker(new URL('./x', import.meta.url))`: the worker script it names, when the app compiled it. */
|
|
735
|
-
workerScript(e) {
|
|
736
|
-
let spec = null;
|
|
737
|
-
if (ts.isStringLiteralLike(e)) {
|
|
738
|
-
spec = e.text;
|
|
739
|
-
}
|
|
740
|
-
else if (ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'URL') {
|
|
741
|
-
const [s, base] = e.arguments ?? [];
|
|
742
|
-
if (s && ts.isStringLiteralLike(s) && base && base.getText() === 'import.meta.url')
|
|
743
|
-
spec = s.text;
|
|
744
|
-
}
|
|
745
|
-
if (!spec || !this.workerScripts?.size)
|
|
746
|
-
return null;
|
|
747
|
-
const file = e.getSourceFile().fileName;
|
|
748
|
-
const target = spec.startsWith('.') ? pathResolve(pathDirname(file), spec) : this.resolveAlias?.(spec, file);
|
|
749
|
-
if (target) {
|
|
750
|
-
const stem = target.replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
|
|
751
|
-
for (const f of [stem + '.ts', stem + '.android.ts', stem + '.tsx', stem + '/index.ts', stem + '/index.android.ts']) {
|
|
752
|
-
const script = this.workerScripts.get(f);
|
|
753
|
-
if (script)
|
|
754
|
-
return script;
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
if (spec.startsWith('~/') || spec.startsWith('@/')) {
|
|
758
|
-
const rel = spec.slice(2).replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
|
|
759
|
-
for (const [key, script] of this.workerScripts) {
|
|
760
|
-
const norm = key.replace(/\\/g, '/');
|
|
761
|
-
if ([`/${rel}.ts`, `/${rel}.android.ts`, `/${rel}.tsx`, `/${rel}/index.ts`, `/${rel}/index.android.ts`].some((s) => norm.endsWith(s)))
|
|
762
|
-
return script;
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
return null;
|
|
766
|
-
}
|
|
767
728
|
/**
|
|
768
729
|
* A function literal stored where untyped code calls it (`global.onmessage = (m: Msg) => …`): jsCall passes
|
|
769
730
|
* JavaScript values, so typed parameters are converted from them inside.
|