@nstudio/nativescript-compiler 9.2.0-alpha.10 → 9.2.0-alpha.11

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 (135) hide show
  1. package/dist/api/ir.js +7 -1
  2. package/dist/driver/cli.js +2 -0
  3. package/dist/driver/compile.js +22 -10
  4. package/dist/driver/unimplemented.js +15 -0
  5. package/dist/kotlin/access.js +22 -4
  6. package/dist/kotlin/arguments.js +5 -0
  7. package/dist/kotlin/builtins.js +0 -4
  8. package/dist/kotlin/calls.js +6 -2
  9. package/dist/kotlin/class-methods.js +9 -3
  10. package/dist/kotlin/components.js +13 -8
  11. package/dist/kotlin/core-api.js +2 -13
  12. package/dist/kotlin/declarations.js +2 -0
  13. package/dist/kotlin/expression-statements.js +5 -4
  14. package/dist/kotlin/functions.js +13 -4
  15. package/dist/kotlin/global-calls.js +11 -0
  16. package/dist/kotlin/literals.js +51 -5
  17. package/dist/kotlin/names.js +2 -2
  18. package/dist/kotlin/native/api.js +9 -1
  19. package/dist/kotlin/native/subclasses.js +4 -3
  20. package/dist/kotlin/native/types.js +8 -5
  21. package/dist/kotlin/operators.js +4 -1
  22. package/dist/kotlin/prototype-calls.js +5 -0
  23. package/dist/kotlin/render.js +62 -0
  24. package/dist/kotlin/statements.js +9 -0
  25. package/dist/kotlin/static-calls.js +4 -3
  26. package/dist/kotlin/types.js +6 -6
  27. package/dist/plugins/native-android.js +7 -3
  28. package/dist/plugins/native-ios.js +2 -0
  29. package/dist/plugins/source.js +73 -23
  30. package/dist/program/app-modules.js +91 -16
  31. package/dist/program/app-paths.js +80 -12
  32. package/dist/program/class-mixins.js +463 -0
  33. package/dist/program/core-facts.js +7 -0
  34. package/dist/program/glob.js +274 -0
  35. package/dist/program/platform.js +32 -4
  36. package/dist/program/program.js +212 -20
  37. package/dist/program/source-lines.js +4 -1
  38. package/dist/program/vite-plugins.js +144 -0
  39. package/dist/semantics/apis/globals.js +2 -2
  40. package/dist/semantics/apis/object.js +1 -0
  41. package/dist/semantics/apis/statics.js +6 -0
  42. package/dist/semantics/ast.js +20 -2
  43. package/dist/semantics/classes.js +36 -1
  44. package/dist/semantics/globals.js +3 -0
  45. package/dist/semantics/lang.js +13 -1
  46. package/dist/semantics/nullish.js +29 -11
  47. package/dist/semantics/refuse-receivers.js +3 -3
  48. package/dist/semantics/refuse-scope.js +2 -7
  49. package/dist/semantics/runtime.js +1 -0
  50. package/dist/semantics/states/value-states.js +1 -1
  51. package/dist/semantics/throws.js +1 -0
  52. package/dist/semantics/translator-methods.js +1 -1
  53. package/dist/semantics/types.js +21 -1
  54. package/dist/swift/access.js +25 -10
  55. package/dist/swift/arguments.js +10 -2
  56. package/dist/swift/assignment.js +12 -1
  57. package/dist/swift/builtins.js +0 -4
  58. package/dist/swift/calls.js +6 -2
  59. package/dist/swift/class-methods.js +3 -3
  60. package/dist/swift/components.js +28 -8
  61. package/dist/swift/construction.js +4 -0
  62. package/dist/swift/core-api.js +9 -12
  63. package/dist/swift/functions.js +13 -2
  64. package/dist/swift/generics.js +5 -1
  65. package/dist/swift/global-calls.js +2 -0
  66. package/dist/swift/literals.js +53 -6
  67. package/dist/swift/names.js +1 -1
  68. package/dist/swift/native/sdk-tables.js +52 -4
  69. package/dist/swift/native/sdk.js +9 -1
  70. package/dist/swift/operators.js +4 -1
  71. package/dist/swift/parameters.js +5 -2
  72. package/dist/swift/placement.js +42 -1
  73. package/dist/swift/prototype-calls.js +17 -2
  74. package/dist/swift/render.js +64 -0
  75. package/dist/swift/results.js +1 -1
  76. package/dist/swift/statements.js +9 -0
  77. package/dist/swift/static-calls.js +8 -3
  78. package/dist/swift/types.js +9 -9
  79. package/dist/targets/android/build.js +13 -9
  80. package/dist/targets/ios/build.js +11 -10
  81. package/dist/targets/ios/dependencies.js +12 -0
  82. package/dist/targets/resources.js +15 -1
  83. package/dist/template/plan.js +105 -8
  84. package/dist/types/adapter-api.d.ts +13 -0
  85. package/dist/types/ir.d.ts +47 -0
  86. package/kit-android/generated/kotlin/org/nativescript/kit/__Objects.kt +102 -7485
  87. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -3
  88. package/kit-android/generated/source-lines.json +1 -1
  89. package/kit-android/src/fromcore/kotlin/org/nativescript/kit/CoreBridge.kt +67 -1
  90. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +26 -0
  91. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +4 -4
  92. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +24 -146
  93. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -281
  94. package/kit-apple/Sources/NativeScriptKit/Core/{Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_91b5f3.swift → Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_fa18e1.swift} +28 -103
  95. package/kit-apple/Sources/NativeScriptKit/Core/__Namespace.Utils.swift +17 -15
  96. package/kit-apple/Sources/NativeScriptKit/Core/application-settings.index.ios.swift +8 -8
  97. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +4 -4
  98. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +7 -7
  99. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.index.ios.swift +2 -1
  100. package/kit-apple/Sources/NativeScriptKit/Core/image-source.index.ios.swift +1 -1
  101. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +34 -244
  102. package/kit-apple/Sources/NativeScriptKit/Core/manifest.json +1 -2
  103. package/kit-apple/Sources/NativeScriptKit/Core/ui.action-bar.index.ios.swift +3 -3
  104. package/kit-apple/Sources/NativeScriptKit/Core/ui.button.index.ios.swift +4 -4
  105. package/kit-apple/Sources/NativeScriptKit/Core/ui.content-view.index.swift +8 -8
  106. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +4 -4
  107. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.index.ios.swift +8 -8
  108. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-common.swift +1 -3
  109. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-helper.view-helper-common.swift +7 -7
  110. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.index.ios.swift +4 -4
  111. package/kit-apple/Sources/NativeScriptKit/Core/ui.html-view.index.ios.swift +4 -4
  112. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.image-common.swift +2 -2
  113. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.index.ios.swift +4 -4
  114. package/kit-apple/Sources/NativeScriptKit/Core/ui.label.index.ios.swift +4 -4
  115. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.absolute-layout.index.ios.swift +4 -4
  116. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.dock-layout.index.ios.swift +4 -4
  117. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.flexbox-layout.index.ios.swift +3 -3
  118. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.grid-layout.index.ios.swift +4 -4
  119. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.stack-layout.index.ios.swift +4 -4
  120. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.wrap-layout.index.ios.swift +4 -4
  121. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +3 -3
  122. package/kit-apple/Sources/NativeScriptKit/Core/ui.page.index.ios.swift +4 -4
  123. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +4 -4
  124. package/kit-apple/Sources/NativeScriptKit/Core/ui.scroll-view.index.ios.swift +4 -4
  125. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.index.ios.swift +4 -4
  126. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.background.ios.swift +1 -1
  127. package/kit-apple/Sources/NativeScriptKit/Core/ui.tab-view.index.ios.swift +4 -4
  128. package/kit-apple/Sources/NativeScriptKit/Core/utils.common.swift +9 -9
  129. package/kit-apple/Sources/NativeScriptKit/Core/utils.layout-helper.index.ios.swift +10 -10
  130. package/kit-apple/Sources/NativeScriptKit/CoreBridge.swift +67 -1
  131. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +4 -0
  132. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +25 -0
  133. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +6 -0
  134. package/package.json +1 -1
  135. package/kit-apple/Sources/NativeScriptKit/Core/Object_toString_charAt_charCodeAt_concat_indexOf_lastIndexOf_and_44_more_fc25df.swift +0 -481
@@ -15,6 +15,8 @@ export function errorArguments(name, args) {
15
15
  const WEB_CLASSES = ['TextEncoder', 'TextDecoder', 'Crypto', 'SubtleCrypto', 'CryptoKey', 'CryptoKeyPair', 'KeyAlgorithm', 'DOMException'];
16
16
  /** The worker API's classes, web classes of a kit that runs workers. */
17
17
  const WORKER_CLASSES = ['Worker', 'MessageEvent', 'ErrorEvent', 'URL'];
18
+ /** Web API classes that have native/kit representations (as opposed to DOM-only element/node interfaces held untyped). */
19
+ export const ALL_WEB_CLASSES = new Set([...WEB_CLASSES, ...WORKER_CLASSES, 'URLSearchParams', 'AbortController', 'AbortSignal', 'Blob', 'File', 'FormData', 'Headers', 'Request', 'Response', 'Event', 'EventTarget', 'CustomEvent', 'CloseEvent', 'WebSocket', 'ReadableStream', 'WritableStream', 'TransformStream']);
18
20
  /** `name` is a web class the kit implements. */
19
21
  export function isWebClass(ledger, name) {
20
22
  return WEB_CLASSES.includes(name) || (ledger.workerGlobals && WORKER_CLASSES.includes(name));
@@ -35,6 +37,7 @@ export const SHARED_LIB_CONSTANTS = {
35
37
  'Symbol.dispose': 'JSSymbol.dispose',
36
38
  'Symbol.asyncDispose': 'JSSymbol.asyncDispose',
37
39
  'Object.prototype': 'JSPrototypes.objectPrototype',
40
+ ...Object.fromEntries(TYPED_ARRAYS.map((t) => [`${t}.BYTES_PER_ELEMENT`, `JS${t}.BYTES_PER_ELEMENT`])),
38
41
  };
39
42
  const LIB_GLOBALS = new Set(['Math', 'JSON', 'Object', 'Array', 'Number', 'Promise', 'console', 'String', 'Boolean', 'Map', 'Set', 'Date', 'RegExp', 'WeakRef', 'Symbol', 'WeakMap', 'WeakSet', 'BigInt']);
40
43
  /** `id` names one of the library's globals itself, not a program's declaration of that name. */
@@ -155,7 +155,7 @@ export function jsKeyOrder(keys) {
155
155
  return [...keys.filter(index).sort((a, b) => Number(a) - Number(b)), ...keys.filter((k) => !index(k))];
156
156
  }
157
157
  /** The kit's names for members a well-known symbol names (`[Symbol.iterator]`, `__@iterator@12` in the checker). */
158
- export const WELL_KNOWN_MEMBERS = { iterator: 'jsSymbolIterator', asyncIterator: 'jsSymbolAsyncIterator', toPrimitive: 'jsToPrimitive', toStringTag: 'jsToStringTag', dispose: 'jsSymbolDispose', asyncDispose: 'jsSymbolAsyncDispose' };
158
+ export const WELL_KNOWN_MEMBERS = { iterator: 'jsSymbolIterator', asyncIterator: 'jsSymbolAsyncIterator', toPrimitive: 'jsToPrimitive', toStringTag: 'jsToStringTag', dispose: 'jsSymbolDispose', asyncDispose: 'jsSymbolAsyncDispose', hasInstance: 'jsHasInstance' };
159
159
  /** A property's name as the checker spells a well-known symbol's (`__@iterator@12`): the kit's member name. */
160
160
  export function wellKnownMember(name) {
161
161
  const m = /^__@(\w+)@\d+$/.exec(name);
@@ -202,6 +202,18 @@ export function isDomGlobalDeclaration(name, decls) {
202
202
  export function isDisposerMember(member) {
203
203
  return member === 'jsSymbolDispose' || member === 'jsSymbolAsyncDispose';
204
204
  }
205
+ /** Well-known symbol methods emitted directly on the class without a dynamic symbol dispatch table (`Symbol.dispose`, `Symbol.asyncDispose`, `Symbol.hasInstance`). */
206
+ export function isDirectSymbolMethod(member) {
207
+ return isDisposerMember(member) || member === 'jsHasInstance';
208
+ }
209
+ /** Framework-hooked dynamic `import('...')` call; null if unhandled. */
210
+ export function hookedDynamicImport(e, hooks) {
211
+ return e.expression.kind === ts.SyntaxKind.ImportKeyword && e.arguments[0] && ts.isStringLiteral(e.arguments[0]) ? (hooks.dynamicImport?.(e.arguments[0].text) ?? null) : null;
212
+ }
213
+ /** Whether the non-nullable form of `t` is an uninstantiated type parameter (`{} as TContext`). */
214
+ export function isTypeParameterType(t, checker) {
215
+ return !!(checker.getNonNullableType(t).flags & ts.TypeFlags.TypeParameter);
216
+ }
205
217
  /** A protocol/interface method's native name, mapping `[Symbol.iterator]` and `[Symbol.asyncIterator]` to their runtime names. */
206
218
  export function protocolMethodName(name, checker, escape) {
207
219
  if (ts.isComputedPropertyName(name)) {
@@ -1,6 +1,7 @@
1
1
  // Which slots may hold null and undefined both, decided once for the program: what each backend's optional alone
2
2
  // can't tell apart, and the program facts that decide it (what a function gives, which variables code reassigns).
3
3
  import ts from 'typescript';
4
+ import { ALL_WEB_CLASSES } from "./globals.js";
4
5
  import { alwaysEnds } from "./lang.js";
5
6
  /** The first of `refused` inside each top-level statement of `sf`: the declaration a refusal leaves out, its module's others kept. */
6
7
  export function refusedStatements(sf, refused) {
@@ -14,7 +15,7 @@ export function refusedStatements(sf, refused) {
14
15
  }
15
16
  return out;
16
17
  }
17
- export function nullishSlots(checker, files, skip, formBoth = () => false, framework = {}) {
18
+ export function nullishSlots(checker, files, skip, formBoth = () => false, framework = {}, signalKind = (n) => framework.signalTypes?.[n]) {
18
19
  const held = new Set(), fields = new Set();
19
20
  const refused = [];
20
21
  const functions = new Map();
@@ -26,7 +27,11 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
26
27
  .filter((x) => !(x.flags & nullish))
27
28
  .every((x) => x.getCallSignatures().length && !x.getProperties().length);
28
29
  const parts = (t) => (t.isUnion() ? t.types : [t]);
29
- const loose = (t) => parts(t).some((x) => x.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown));
30
+ const domOnly = (x) => {
31
+ const sym = x.getSymbol();
32
+ return !!sym?.declarations?.length && sym.declarations.every((d) => /[\\/]lib\.dom[\w.]*\.d\.ts$/.test(d.getSourceFile().fileName)) && !ALL_WEB_CLASSES.has(sym.name);
33
+ };
34
+ const loose = (t) => parts(t).some((x) => !!(x.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) || domOnly(x));
30
35
  const hasNull = (t) => !loose(t) && parts(t).some((x) => x.flags & ts.TypeFlags.Null);
31
36
  const both = (t) => hasNull(t) && parts(t).some((x) => x.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void));
32
37
  // A result typed `void | null` is one callers ignore.
@@ -109,9 +114,16 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
109
114
  return (op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.AmpersandAmpersandToken || op === ts.SyntaxKind.QuestionQuestionToken) && tested(p);
110
115
  };
111
116
  // A parameter whose value goes on (printed, stored, passed) where it may still be null or undefined both.
117
+ const signalSet = (x) => {
118
+ if (!ts.isCallExpression(x.parent) || x.parent.arguments[0] !== x || !ts.isPropertyAccessExpression(x.parent.expression) || x.parent.expression.name.text !== 'set')
119
+ return false;
120
+ const recv = checker.getTypeAtLocation(x.parent.expression.expression);
121
+ const name = (recv.aliasSymbol ?? recv.getSymbol())?.name;
122
+ return !!name && !!signalKind(name);
123
+ };
112
124
  const escapes = (d) => {
113
125
  const sym = d.name && checker.getSymbolAtLocation(d.name);
114
- return !sym || (refs.get(sym) ?? []).some((r) => both(checker.getTypeAtLocation(r)) && !tested(r));
126
+ return !sym || (refs.get(sym) ?? []).some((r) => both(checker.getTypeAtLocation(r)) && !tested(r) && !signalSet(r));
115
127
  };
116
128
  /**
117
129
  * A slot typed `T | null` whose value form holds undefined too (a missing value reaches it) and tells them apart
@@ -229,11 +241,14 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
229
241
  return false;
230
242
  };
231
243
  // Any parameter or result of `fn` that may hold both, refused as `why`.
232
- const refuseBoth = (fn, why) => {
244
+ const refuseBoth = (fn, why, coverUnobserved = false) => {
233
245
  for (const p of fn.parameters) {
234
246
  const t = typeOf(p);
235
- if (both(t) && oneKind(t))
236
- refuse(p, `${why} (\`${text(t)}\`)`);
247
+ if (both(t) && oneKind(t)) {
248
+ if (coverUnobserved && !observes(p) && !escapes(p))
249
+ continue;
250
+ refuse(p, `${why} (\`${text(t)}\`)`, coverUnobserved && named(p) && !observes(p) ? { kind: 'value', slot: p } : undefined);
251
+ }
237
252
  }
238
253
  const ret = returnOf(fn);
239
254
  if (!ts.isConstructorDeclaration(fn) && ret && bothResult(ret) && oneKind(ret))
@@ -303,7 +318,7 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
303
318
  const { members: family, why } = familyOf(fn);
304
319
  if (why) {
305
320
  for (const x of family)
306
- refuseBoth(x, why);
321
+ refuseBoth(x, why, why === 'a method an interface declares');
307
322
  continue;
308
323
  }
309
324
  const width = Math.max(...family.map((x) => x.parameters.length));
@@ -385,7 +400,7 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
385
400
  })()
386
401
  : checker.getContextualType(fn);
387
402
  const ctx = contextual?.getNonNullableType().getCallSignatures()[0];
388
- if (!ctx) {
403
+ if (!ctx || ctx.getDeclaration() === fn) {
389
404
  holdSignature(fn);
390
405
  continue;
391
406
  }
@@ -441,6 +456,9 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
441
456
  for (const x of parts(t)) {
442
457
  if (!(x.flags & ts.TypeFlags.Object) || x.getCallSignatures().length)
443
458
  continue;
459
+ const symName = (x.aliasSymbol ?? x.getSymbol())?.name ?? '';
460
+ if (symName === 'OutputEmitterRef' || symName === 'EventEmitter')
461
+ continue;
444
462
  const args = x.objectFlags & ts.ObjectFlags.Reference ? checker.getTypeArguments(x) : (x.aliasTypeArguments ?? []);
445
463
  for (const a of [...args, ...checker.getIndexInfosOfType(x).map((i) => i.type)]) {
446
464
  const r = nested(a, depth + 1, seen);
@@ -453,7 +471,7 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
453
471
  // Only an array's or Set's element and a Map's value have a form of their own (`Form.element`).
454
472
  const collectionElement = (t) => {
455
473
  const x = checker.getNonNullableType(t), name = x.getSymbol()?.name ?? '';
456
- if (!checker.isArrayType(x) && !['Set', 'ReadonlySet', 'Map', 'ReadonlyMap'].includes(name))
474
+ if (!checker.isArrayType(x) && !['ReadonlyArray', 'Set', 'ReadonlySet', 'Map', 'ReadonlyMap'].includes(name))
457
475
  return undefined;
458
476
  return checker.getTypeArguments(x)[name === 'Map' || name === 'ReadonlyMap' ? 1 : 0];
459
477
  };
@@ -477,7 +495,7 @@ export function nullishSlots(checker, files, skip, formBoth = () => false, frame
477
495
  else if (ts.isPropertySignature(n) && ts.isIdentifier(n.name) && both(typeOf(n)))
478
496
  fields.add(n);
479
497
  else if ((ts.isGetAccessorDeclaration(n) || ts.isSetAccessorDeclaration(n)) && n.body)
480
- refuseBoth(n, 'an accessor that may take or give null or undefined both');
498
+ refuseBoth(n, 'an accessor that may take or give null or undefined both', ts.isSetAccessorDeclaration(n));
481
499
  if ((ts.isVariableDeclaration(n) || ts.isParameter(n) || ts.isPropertyDeclaration(n) || ts.isPropertySignature(n)) && n.name && checker.getSymbolAtLocation(n.name))
482
500
  checkNested(n, typeOf(n));
483
501
  if (ts.isFunctionLike(n) && !ts.isConstructorDeclaration(n))
@@ -806,7 +824,7 @@ export function downcast(checker, e, own) {
806
824
  if (!cls || !(cls.flags & ts.SymbolFlags.Class) || !own(cls.valueDeclaration) || from.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown) || from === to)
807
825
  return false;
808
826
  // A class extending a native or the kit's class keeps its checked cast: such objects are not all read by name.
809
- for (let t = to; t; t = checker.getBaseTypes(t)[0]) {
827
+ for (let t = to; t?.isClassOrInterface(); t = checker.getBaseTypes(t)[0]) {
810
828
  if (!own(t.getSymbol()?.valueDeclaration))
811
829
  return false;
812
830
  if (!(t.flags & ts.TypeFlags.Object) || !(t.objectFlags & ts.ObjectFlags.ClassOrInterface))
@@ -2,7 +2,7 @@
2
2
  // `.apply` on a value of another type, a class's prototype read for what the class declares there, a buffer type's
3
3
  // prototype the runtimes have no object for. Each decision is made here once; both backends throw what it returns.
4
4
  import ts from 'typescript';
5
- import { isLibDeclaration, isWriteTarget } from "./ast.js";
5
+ import { declaresThis, isLibDeclaration, isWriteTarget } from "./ast.js";
6
6
  import { aliasedPrototypeMember } from "./lang.js";
7
7
  import { programBase } from "./classes.js";
8
8
  import { BUFFER_TYPES, TYPED_ARRAYS } from "./globals.js";
@@ -72,7 +72,7 @@ export function builtinMethodReceiver(e, checker, library) {
72
72
  const member = checker.getSymbolAtLocation(target.name);
73
73
  if (!libDeclared(member) || !member.declarations.every((d) => ts.isMethodSignature(d) || ts.isMethodDeclaration(d)))
74
74
  return undefined;
75
- if (member.declarations.some((d) => ts.isInterfaceDeclaration(d.parent) && ['Function', 'CallableFunction', 'NewableFunction'].includes(d.parent.name.text)))
75
+ if (member.declarations.some((d) => ts.isInterfaceDeclaration(d.parent) && ['Function', 'CallableFunction', 'NewableFunction', 'PropertyDescriptor'].includes(d.parent.name.text)))
76
76
  return undefined;
77
77
  let root = value;
78
78
  while (ts.isPropertyAccessExpression(root) || ts.isElementAccessExpression(root))
@@ -112,7 +112,7 @@ export function programMethodReceiver(e, checker, library) {
112
112
  if (!member || libDeclared(member))
113
113
  return undefined;
114
114
  const decl = member.declarations?.find((d) => ts.isMethodDeclaration(d) && !!d.body) ?? member.valueDeclaration;
115
- if (!decl || !(ts.isMethodDeclaration(decl) || ts.isMethodSignature(decl)))
115
+ if (!decl || !(ts.isMethodDeclaration(decl) || (ts.isMethodSignature(decl) && !declaresThis(decl))))
116
116
  return undefined;
117
117
  const receiver = e.arguments[0];
118
118
  const plain = (x) => x.kind === ts.SyntaxKind.ThisKeyword || ts.isIdentifier(x) || ts.isLiteralExpression(x) || (ts.isPropertyAccessExpression(x) && plain(x.expression));
@@ -10,13 +10,8 @@ function thisOwner(e) {
10
10
  * `this` in a function declaration that reads its `arguments` too: the function then takes its arguments as one list,
11
11
  * which leaves no parameter for the receiver its calls give it.
12
12
  */
13
- export function functionThis(e, front) {
14
- if (front.library || e.kind !== ts.SyntaxKind.ThisKeyword)
15
- return undefined;
16
- const owner = thisOwner(e);
17
- if (!owner || !ts.isFunctionDeclaration(owner) || !owner.body || declaresThis(owner) || !front.readsArguments(owner))
18
- return undefined;
19
- return { id: 'function-this', what: '`this` in a function that also reads `arguments`', node: e };
13
+ export function functionThis(_e, _front) {
14
+ return undefined;
20
15
  }
21
16
  /**
22
17
  * `this` in a function expression outside any class, stored in a typed function slot of an object
@@ -222,6 +222,7 @@ const SHARED = [
222
222
  'jsSearch',
223
223
  'jsSet',
224
224
  'jsSetInterval',
225
+ 'jsSetPrototypeOf',
225
226
  'jsSetTimeout',
226
227
  'jsShiftLeft',
227
228
  'jsShiftRight',
@@ -94,7 +94,7 @@ export class ValueStates {
94
94
  const b = this.backend;
95
95
  const found = b.lenient || b.library
96
96
  ? { held: new Set(), fields: new Set(), refused: [], functions: new Map() }
97
- : nullishSlots(b.checker, b.sourceFiles, (f) => b.pluginFiles.has(f.fileName), (d) => this.formNullish(d), b.framework.hooks);
97
+ : nullishSlots(b.checker, b.sourceFiles, (f) => b.pluginFiles.has(f.fileName), (d) => this.formNullish(d), b.framework.hooks, (n) => b.framework.signalKind(n));
98
98
  // An element, callback parameter or loop variable the analysis can't hold: one nil, read as undefined, where
99
99
  // nothing tells null from undefined in it; `JSNullish<T>` where something does.
100
100
  found.refused = found.refused.filter(([, , cover]) => {
@@ -22,6 +22,7 @@ const THROWING_BUILTINS = new Set([
22
22
  'String.replaceAll',
23
23
  'Date.toISOString',
24
24
  'Object.assign',
25
+ 'Object.setPrototypeOf',
25
26
  'Object.fromEntries',
26
27
  'Object.defineProperty',
27
28
  'Object.defineProperties',
@@ -430,7 +430,7 @@ export const frontMethods = traceMethods('front', {
430
430
  */
431
431
  implicitThis(fn) {
432
432
  if (!this.ledger.implicitThisUnconstructed)
433
- return ts.isFunctionDeclaration(fn) && !!fn.body && !fn.parameters.some((q) => ts.isIdentifier(q.name) && q.name.text === 'this') && thisNodes(fn).length > 0 && !frontMethods.readsArguments.call(this, fn);
433
+ return ts.isFunctionDeclaration(fn) && !!fn.body && !fn.parameters.some((q) => ts.isIdentifier(q.name) && q.name.text === 'this') && thisNodes(fn).length > 0;
434
434
  if (!ts.isFunctionDeclaration(fn) || !fn.body || !fn.name || declaresThis(fn) || fn.parameters[0]?.name.getText() === 'this' || !thisNodes(fn).length)
435
435
  return false;
436
436
  const name = fn.name.text;
@@ -3,6 +3,20 @@ import { isCoreDeclaration } from "../program/core-facts.js";
3
3
  import { isLibDeclaration } from "./ast.js";
4
4
  import { BUFFER_TYPES, ERRORS, UNSUPPORTED_LIB_GLOBALS } from "./globals.js";
5
5
  import { rethrowUnlessRefused } from "./refusals.js";
6
+ /** Classifies a `ValueModule` object type: an ES module namespace (`typeof import('...')`), a program `namespace`, or null. */
7
+ export function valueModuleKind(t) {
8
+ const sym = t.flags & ts.TypeFlags.Object ? t.getSymbol() : undefined;
9
+ if (!sym || !(sym.flags & ts.SymbolFlags.ValueModule))
10
+ return null;
11
+ const decl = sym.valueDeclaration;
12
+ if (!decl)
13
+ return null;
14
+ if (ts.isSourceFile(decl))
15
+ return 'module';
16
+ if (ts.isModuleDeclaration(decl) && !decl.getSourceFile().isDeclarationFile)
17
+ return decl;
18
+ return null;
19
+ }
6
20
  const CORE_TYPES = {
7
21
  AnimationPromise: 'void-promise',
8
22
  AnimationDefinition: 'untyped',
@@ -450,9 +464,15 @@ export function nonNullableInner(t, name, args) {
450
464
  export function nonOptionalSpelling(type) {
451
465
  return isUntyped(spelledType(type)) ? type : type.replace(/\?$/, '');
452
466
  }
453
- /** A JSDoc `@constructor` function in a JS module (no class/interface/enum/ambient declaration): no native class exists for it. */
467
+ /** A JSDoc `@constructor`, `@typedef`, or `@callback` in a JS module (no class/interface/enum/ambient declaration): no native class exists for it. */
454
468
  export function isJsDocConstructorFunction(sym) {
469
+ if (sym?.declarations?.length && sym.declarations.every((d) => ts.isJSDocTypedefTag(d) || ts.isJSDocCallbackTag(d)))
470
+ return true;
455
471
  if (!sym?.valueDeclaration || !(ts.isFunctionDeclaration(sym.valueDeclaration) || ts.isFunctionExpression(sym.valueDeclaration) || ts.isVariableDeclaration(sym.valueDeclaration)))
456
472
  return false;
457
473
  return !sym.declarations?.some((d) => ts.isClassLike(d) || ts.isInterfaceDeclaration(d) || ts.isEnumDeclaration(d) || d.getSourceFile().isDeclarationFile);
458
474
  }
475
+ /** An intersection containing a mapped or utility-mapped member (`{ a?: string } & Partial<Record<K, string>>`): held untyped. */
476
+ export function hasMappedIntersection(t) {
477
+ return t.types.some((u) => !!(u.objectFlags & ts.ObjectFlags.Mapped) || (!!u.aliasSymbol && ['Partial', 'Record', 'Pick', 'Omit', 'Required', 'Readonly'].includes(u.aliasSymbol.name)));
478
+ }
@@ -5,7 +5,7 @@ import { LIB_CONSTANTS, MATH, isTypedArrayType } from "./library.js";
5
5
  import { mathFunctionValue } from "../semantics/apis/math.js";
6
6
  import { CONSOLE } from "../semantics/apis/console.js";
7
7
  import { libFunctionValueKind } from "../semantics/apis/statics.js";
8
- import { ERRORS, TYPED_ARRAYS, isLibGlobal } from "../semantics/globals.js";
8
+ import { ERRORS, isLibGlobal } from "../semantics/globals.js";
9
9
  import { spell, escapingFunction, functionParts, hasTopLevelArrow, ident, identPath, isFunctionType, isOptional, openSwiftChain, optionalType, splitTopLevel, swiftString, RT, lenientReader } from "./syntax.js";
10
10
  import { elementReceiverCell, keyName, observerSlot, place, receiverCell, receiverSlot, isEnumObject, nullishField } from "../semantics/placement.js";
11
11
  import { ambientAddedMemberOf, augmentedPropertyRead, functionProperty, uncheckedMatch, wellKnownMember, isSelf } from "../semantics/lang.js";
@@ -18,7 +18,7 @@ import { tested } from "./native/bridging.js";
18
18
  import { rethrowUnlessRefused } from "../semantics/refusals.js";
19
19
  import { byKey, symbolField } from "../semantics/spelled.js";
20
20
  import { definedField } from "../semantics/shapes.js";
21
- import { baseMethod, declaredClassName, heldClassName } from "../semantics/classes.js";
21
+ import { baseMethod, declaredClassName, heldClassName, prototypeClassSymbol } from "../semantics/classes.js";
22
22
  import { MODELLED_BUFFER_PROTOTYPES } from "../semantics/refuse-receivers.js";
23
23
  export const accessMethods = {
24
24
  /** The Swift type of the declaration a getter overrides, when the override narrows it; null otherwise. */
@@ -136,9 +136,15 @@ export const accessMethods = {
136
136
  // `ArrayBuffer.prototype`: an object of the class's tag, all a program reads of it.
137
137
  if (name === 'prototype' && ts.isIdentifier(target) && MODELLED_BUFFER_PROTOTYPES.has(target.text) && isLibGlobal(this, target))
138
138
  return `JS${target.text}.jsPrototype`;
139
- // `Cls.prototype` (library mode): what script defines there, which the class's instances read.
140
- if (name === 'prototype' && (this.library || this.definedOn(e)) && this.resolve(target)?.flags & ts.SymbolFlags.Class)
141
- return `JSPrototypes.of(${this.expr(target).replace(/(\.self)?$/, '.self')})`;
139
+ // `Function.prototype`: a function that does nothing.
140
+ if (name === 'prototype' && ts.isIdentifier(target) && target.text === 'Function' && isLibDeclaration(this.resolve(target)?.declarations?.[0]))
141
+ return '({ (_: [Any?]) throws -> Any? in nil } as JSFunction)';
142
+ // `Cls.prototype`: what script defines there, which the class's instances read.
143
+ const protoSym = prototypeClassSymbol(target, name, this);
144
+ if (protoSym) {
145
+ const cls = this.type(this.checker.getDeclaredTypeOfSymbol(protoSym), e).replace(/<.*$/, '');
146
+ return `JSPrototypes.of(${cls}.self)`;
147
+ }
142
148
  if (name === 'prototype' && this.library && this.typeOf(target).endsWith('.Type'))
143
149
  return `JSPrototypes.of(${this.expr(target)})`;
144
150
  // `value.constructor`: its class, which script tests for static members.
@@ -150,15 +156,10 @@ export const accessMethods = {
150
156
  // `value.constructor.name`: its class's name.
151
157
  if (name === 'name' && ts.isPropertyAccessExpression(target) && target.name.text === 'constructor' && !isWriteTarget(e))
152
158
  return `${RT.jsConstructorName}(${this.coerce(target.expression, 'Any?')})`;
153
- // `Function.prototype`: a function that does nothing.
154
- if (name === 'prototype' && ts.isIdentifier(target) && target.text === 'Function' && isLibDeclaration(this.resolve(target)?.declarations?.[0]))
155
- return '({ (_: [Any?]) throws -> Any? in nil } as JSFunction)';
156
159
  if (ts.isIdentifier(target) && isLibGlobal(this, target)) {
157
160
  const constant = LIB_CONSTANTS[`${target.text}.${name}`];
158
161
  if (constant)
159
162
  return constant;
160
- if (name === 'BYTES_PER_ELEMENT' && TYPED_ARRAYS.includes(target.text))
161
- return `JS${target.text}.BYTES_PER_ELEMENT`;
162
163
  // `const round = Math.round`: the function as a value.
163
164
  const mathValue = target.text === 'Math' ? mathFunctionValue(name) : null;
164
165
  if (mathValue)
@@ -172,6 +173,12 @@ export const accessMethods = {
172
173
  }
173
174
  if (libFn === 'fromCharCode')
174
175
  return this.convert(`{ (__args: JSRest<Double>) -> String in ${RT.jsFromCharCode}(codes: __args.storage) }`, '(JSRest<Double>) throws -> String', this.typeOf(e));
176
+ if (libFn === 'fromCodePoint')
177
+ return this.convert(`{ (__args: JSRest<Double>) throws -> String in try ${RT.jsFromCodePoint}(codes: __args.storage) }`, '(JSRest<Double>) throws -> String', this.typeOf(e));
178
+ if (libFn === 'mathRandom')
179
+ return this.convert('{ () -> Double in Double.random(in: 0..<1) }', '() throws -> Double', this.typeOf(e));
180
+ if (libFn === 'mathVariadic')
181
+ return this.convert(`{ (__args: JSRest<Double>) -> Double in ${name === 'min' ? RT.jsMathMin : RT.jsMathMax}(values: __args.storage) }`, '(JSRest<Double>) throws -> Double', this.typeOf(e));
175
182
  if (libFn === 'typedArrayFrom')
176
183
  return this.convert(`{ (__v: Any?) throws -> JS${target.text} in try JS${target.text}.from(__v) }`, `(Any?) throws -> JS${target.text}`, this.typeOf(e));
177
184
  if (libFn === 'isArray')
@@ -568,6 +575,14 @@ export const accessMethods = {
568
575
  const rt = this.typeOf(e);
569
576
  return isUntyped(spelledType(rt)) || isWriteTarget(e) ? code : this.fromAnyCode(code, rt, true);
570
577
  }
578
+ // A homogeneous Swift tuple indexed dynamically (`next[startIndex]`): switch on the integer index.
579
+ if (this.typeOf(e.expression).startsWith('(') && this.checker.isTupleType(receiverType)) {
580
+ const parts = splitTopLevel(this.typeOf(e.expression).slice(1, -1));
581
+ if (parts.length && parts.every((x) => x === parts[0])) {
582
+ const cases = parts.map((_, k) => `case ${k}: return __t.${k}`).join('; ');
583
+ return `{ (__t: ${this.typeOf(e.expression)}, __i: Int) -> ${parts[0]} in switch __i { ${cases}; default: return __t.0 } }(${target}, Int(${this.toNumber(key)}))`;
584
+ }
585
+ }
571
586
  // A computed key on an object (`this[side + 'Drawer']`): its members by name.
572
587
  if (this.isObjectRef(e.expression)) {
573
588
  const code = `${target}${q}[jsKey: ${this.propertyKey(key)}]`;
@@ -95,8 +95,16 @@ export const argumentsMethods = {
95
95
  const impl = sig?.getDeclaration() && implementationOf(sig.getDeclaration());
96
96
  const params = impl ? impl.parameters.map((p) => this.checker.getSymbolAtLocation(p.name)).filter(Boolean) : (sig?.getParameters() ?? []);
97
97
  const target = impl ?? sig?.getDeclaration();
98
- if (target && !ts.isJSDocSignature(target) && this.readsArguments(target))
99
- return [this.packed(all, 'JSArray<Any?>', this.restSlot(e, 'Any?'))];
98
+ if (target && !ts.isJSDocSignature(target) && this.readsArguments(target)) {
99
+ const packed = [this.packed(all, 'JSArray<Any?>', this.restSlot(e, 'Any?'))];
100
+ if (ts.isFunctionDeclaration(target) && this.takesThis(target) && ts.isCallExpression(e)) {
101
+ if (ts.isIdentifier(e.expression))
102
+ packed.unshift('nil');
103
+ else if (ts.isPropertyAccessExpression(e.expression) && this.isNamespace(e.expression.expression))
104
+ packed.unshift(this.coerce(e.expression.expression, 'Any?'));
105
+ }
106
+ return packed;
107
+ }
100
108
  const out = [];
101
109
  const restAt = params.findIndex((p) => p.valueDeclaration && ts.isParameter(p.valueDeclaration) && p.valueDeclaration.dotDotDotToken);
102
110
  // A function type's rest parameter too (`mainThreadify(fn)` gives `(...args) => void`, or `String.fromCharCode.bind(String)`): Swift's function type takes it as `JSRest`.
@@ -1,6 +1,6 @@
1
1
  // Assignment as Swift: prefix and postfix updates, compound assignment and the reads and writes they make.
2
2
  import ts from 'typescript';
3
- import { ident, isNullish, negation, swiftString, throwingSetter, RT } from "./syntax.js";
3
+ import { ident, isNullish, negation, splitTopLevel, swiftString, throwingSetter, RT } from "./syntax.js";
4
4
  import { asOperation, assignmentOf } from "../semantics/lang.js";
5
5
  import { assignedTo, negatedCell } from "../semantics/placement.js";
6
6
  import { notedField } from "../semantics/shapes.js";
@@ -248,6 +248,17 @@ export const assignmentMethods = {
248
248
  // An array written at a key that may be no index (`frames[time]`, time untyped): as script writes it.
249
249
  if (ts.isElementAccessExpression(left) && isKit(spelledType(this.typeOf(left.expression).replace(/[?!]$/, '')), 'JSArray') && this.typeOf(left.argumentExpression) !== 'Double')
250
250
  return `${RT.jsSet}(${this.expr(left.expression)}, ${this.propertyKey(left.argumentExpression)}, ${this.stored(right, left, 'Any?', checks)})`;
251
+ // A homogeneous Swift tuple indexed dynamically (`next[startIndex] = start`): switch on the integer index.
252
+ if (ts.isElementAccessExpression(left) && this.typeOf(left.expression).startsWith('(') && this.checker.isTupleType(this.checker.getNonNullableType(this.checker.getTypeAtLocation(left.expression)))) {
253
+ const parts = splitTopLevel(this.typeOf(left.expression).slice(1, -1));
254
+ if (parts.length && parts.every((x) => x === parts[0])) {
255
+ const recv = this.expr(left.expression);
256
+ const idx = this.toNumber(left.argumentExpression);
257
+ const val = this.stored(right, left, parts[0], checks);
258
+ const cases = parts.map((_, k) => `case ${k}: ${recv}.${k} = __v`).join('; ');
259
+ return `{ (__i: Int, __v: ${parts[0]}) -> ${parts[0]} in switch __i { ${cases}; default: break }; return __v }(Int(${idx}), ${val})`;
260
+ }
261
+ }
251
262
  if (ts.isElementAccessExpression(left) && this.isAny(left.expression))
252
263
  return `${RT.jsSet}(${this.expr(left.expression)}, ${this.propertyKey(left.argumentExpression)}, ${this.stored(right, left, 'Any?', checks)})`;
253
264
  if (this.library && this.holdsMethods(left) && this.carriesMethod(right)) {
@@ -563,8 +563,6 @@ export const builtinMethods = {
563
563
  const fn = name === 'replace' ? RT.jsReplace : RT.jsReplaceAll;
564
564
  // A function value: called with the match, each group (undefined where it took no part), the match's index and the string.
565
565
  if (!(ts.isArrowFunction(second) || ts.isFunctionExpression(second)) && this.checker.getTypeAtLocation(second).getCallSignatures().length) {
566
- if (name === 'replaceAll')
567
- throw this.error(e, 'replaceAll with a function');
568
566
  // A conditional's branches are each held untyped: adapted to one function type, a rest would not take the arguments.
569
567
  const bare = ts.skipOuterExpressions(second);
570
568
  const f = ts.isConditionalExpression(bare) ? `(${this.cond(bare.condition)} ? ${this.coerce(bare.whenTrue, 'Any?')} : ${this.coerce(bare.whenFalse, 'Any?')})` : this.isAny(second) ? this.expr(second) : this.convert(this.expr(second), this.typeOf(second), 'Any?');
@@ -572,8 +570,6 @@ export const builtinMethods = {
572
570
  }
573
571
  if (!(ts.isArrowFunction(second) || ts.isFunctionExpression(second)))
574
572
  return `${fn}(${s}, ${r}, ${this.str(second)})`;
575
- if (name === 'replaceAll')
576
- throw this.error(e, 'replaceAll with a function');
577
573
  // The replacer gets the match, then each group.
578
574
  const m = this.fresh('__match');
579
575
  // The match, each group (undefined where it took no part), the index, the input, then the groups object.
@@ -4,12 +4,13 @@ import { LIST_APPLIED, isTypedArrayType } from "./library.js";
4
4
  import { isLibGlobal } from "../semantics/globals.js";
5
5
  import { comparedToNullish, functionParts, hasTopLevelArrow, ident, isFunctionType, isOptional, isSymbolAsyncIterator, openSwiftChain, optionalType, swiftString, RT } from "./syntax.js";
6
6
  import { assertedReceiverCell, nullishField } from "../semantics/placement.js";
7
- import { intlConstructor, isDomGlobalDeclaration, isObjectToStringCall, mergedInterfaceMemberOf, statementLevel, isArguments, isSelf } from "../semantics/lang.js";
7
+ import { hookedDynamicImport, intlConstructor, isDomGlobalDeclaration, isObjectToStringCall, mergedInterfaceMemberOf, statementLevel, isArguments, isSelf } from "../semantics/lang.js";
8
8
  import { isLibDeclaration, isSymbolIterator } from "../semantics/ast.js";
9
9
  import { isStatic } from "../semantics/throws.js";
10
10
  import { callableSignal, mayBeUnset } from "../semantics/signals.js";
11
11
  import { baseMethod } from "../semantics/classes.js";
12
12
  import { isKit, isUntyped, spelledType } from "../semantics/types.js";
13
+ import { isKitInstanceMethod } from "../program/core-facts.js";
13
14
  export const callsMethods = {
14
15
  /** How many parameters the called function declares (JavaScript ignores extra arguments). */
15
16
  arity(e) {
@@ -84,6 +85,9 @@ export const callsMethods = {
84
85
  return this.signalRead(callee, (code) => (this.nullSignalRead(e) ? this.marks.implicitOf(code) : code));
85
86
  if (callee.kind === ts.SyntaxKind.SuperKeyword)
86
87
  throw this.error(e, 'super() outside the start of a constructor');
88
+ const dynImport = hookedDynamicImport(e, this.framework.hooks);
89
+ if (dynImport)
90
+ return dynImport;
87
91
  // `getWindow<UIWindow>?.()`: the type arguments are only TypeScript's, and a function declaration is always there.
88
92
  const declaredFunction = (x) => ts.isIdentifier(x) && !!this.resolve(x)?.declarations?.some(ts.isFunctionDeclaration);
89
93
  if (ts.isExpressionWithTypeArguments(callee) && (!e.questionDotToken || declaredFunction(callee.expression)))
@@ -138,7 +142,7 @@ export const callsMethods = {
138
142
  // `callback?.(x)` of a parameter declared present: Swift has it as non-optional, and the call is a plain one.
139
143
  const param = ts.isIdentifier(callee) ? this.resolve(callee)?.valueDeclaration : undefined;
140
144
  const presentParam = !!param && ts.isParameter(param) && !param.questionToken && !param.initializer && !this.states.mayBeNull(param) && isFunctionType(this.typeOf(callee));
141
- if (e.questionDotToken && !presentParam && !this.core.isKitMethod(callee) && !declaredMethod && !declaredFunction(callee)) {
145
+ if (e.questionDotToken && !presentParam && !isKitInstanceMethod(this.core, callee) && !declaredMethod && !declaredFunction(callee)) {
142
146
  // A field narrowed to a function already reads unwrapped.
143
147
  const fn = this.expr(callee);
144
148
  return fn.endsWith('!') ? `${fn}(${this.args(e).join(', ')})` : `${fn}?(${this.args(e).join(', ')})`;
@@ -6,7 +6,7 @@ import { isStatic } from "../semantics/throws.js";
6
6
  import { COLLECTION_OVERRIDE_METHODS, collectionBaseInfo, programBase, uncheckedIteratorResult } from "../semantics/classes.js";
7
7
  import { namesMembersBySymbol } from "../semantics/read-sites.js";
8
8
  import { fixedKey } from "../semantics/translator-methods.js";
9
- import { isDisposerMember } from "../semantics/lang.js";
9
+ import { isDirectSymbolMethod } from "../semantics/lang.js";
10
10
  export const classMethodsMethods = {
11
11
  computedMethods(k) {
12
12
  const { cls, name, expando, lines } = k;
@@ -128,8 +128,8 @@ export const classMethodsMethods = {
128
128
  }
129
129
  return;
130
130
  }
131
- if (keyed && isDisposerMember(keyed.member)) {
132
- lines.push(' ' + this.memberFunc(m, keyed.member));
131
+ if (keyed && isDirectSymbolMethod(keyed.member)) {
132
+ lines.push(' ' + this.memberFunc(m, keyed.member, isStatic(m) ? 'class ' : ''));
133
133
  return;
134
134
  }
135
135
  if (keyed)
@@ -4,7 +4,7 @@ import { resultSlot } from "../semantics/placement.js";
4
4
  import { capturesThis, escapingParam, ident, isFunctionType, isMethodValue, isOptional, metatype, nullishType, optionalType, swiftString, withoutThenables, RT } from "./syntax.js";
5
5
  import { equalOption } from "../semantics/signals.js";
6
6
  import { isTemplateMethod } from "../semantics/trust.js";
7
- import { hasModifier } from "../semantics/ast.js";
7
+ import { extendsHeritage, hasModifier, nonSuperStatements } from "../semantics/ast.js";
8
8
  import { nullableTypeNode, resultsAreUndefinedElements } from "../semantics/lang.js";
9
9
  import { implementedOptionalMembers } from "../semantics/shapes.js";
10
10
  import { isAsync, isStatic } from "../semantics/throws.js";
@@ -271,22 +271,38 @@ export const componentMethods = {
271
271
  this.declare(m.name.text, { kind: 'var', type: t });
272
272
  lines.push(` var ${ident(m.name.text)}: ${t}`);
273
273
  }
274
+ // If the component keeps a real superclass (e.g. `@Component extends @Directive`), chain `super.init()` before constructor body.
275
+ const baseCls = this.sourceBase(cls);
276
+ const baseThrows = !!baseCls && this.throwsInfo.initThrows(baseCls);
277
+ if (baseCls) {
278
+ inits.push(` ${baseThrows ? 'try ' : ''}super.init()`);
279
+ }
274
280
  // The constructor's body runs once every field is set; what it throws is reported, as a failed creation is.
275
- if (ctor?.body?.statements.length) {
281
+ const bodyStmts = nonSuperStatements(ctor);
282
+ if (bodyStmts.length) {
276
283
  this.indent = ' ';
277
- const body = this.statements([...ctor.body.statements]);
278
- inits.push(` ${this.throwsInfo.statements(ctor.body.statements) ? RT.jsReport : 'do'} {\n${body.join('\n')}\n }`);
284
+ const body = this.statements([...bodyStmts]);
285
+ inits.push(` ${this.throwsInfo.statements(bodyStmts) ? RT.jsReport : 'do'} {\n${body.join('\n')}\n }`);
279
286
  }
280
287
  this.indent = '';
281
- const throws = convenienceZeroArg || fieldThrows ? ' throws' : '';
288
+ const throws = convenienceZeroArg || fieldThrows || baseThrows ? ' throws' : '';
282
289
  if (throws && cls.name)
283
290
  this.throwingInits.add(cls.name.text);
284
- lines.push(` init(${propParams.join(', ')})${throws} {`, ...inits, ' }');
291
+ const overrideInit = !!baseCls && !propParams.length ? 'override ' : '';
292
+ lines.push(` ${overrideInit}init(${propParams.join(', ')})${throws} {`, ...inits, ' }');
285
293
  if (convenienceZeroArg) {
286
294
  lines.push(` convenience init() throws {\n try self.init(${ctorInjectVals.join(', ')})\n }`);
287
295
  }
288
296
  return lines;
289
297
  },
298
+ /** The Swift superclass clause (`: Base<...>`) for a component that keeps a real superclass, else empty. */
299
+ componentSuperclass(cls) {
300
+ const heritage = extendsHeritage(cls);
301
+ const appBase = this.sourceBase(cls);
302
+ if (!heritage || !appBase)
303
+ return '';
304
+ return `: ${this.className(appBase)}${this.typeArguments(heritage, appBase)}`;
305
+ },
290
306
  /** Static members a component class adds for the framework. */
291
307
  componentStatics(cls) {
292
308
  return this.framework.hooks.componentStatics?.(this, cls) ?? [];
@@ -319,8 +335,12 @@ export const componentMethods = {
319
335
  },
320
336
  /** Whether a component's method or getter throws, so its caller in `render()` reports what it throws. */
321
337
  memberThrows(cls, name) {
322
- const m = cls.members.find((x) => x.name && ts.isIdentifier(x.name) && x.name.text === name);
323
- return !!m && !isAsync(m) && this.throwsInfo.fn(m);
338
+ for (let cur = cls; cur; cur = this.sourceBase(cur)) {
339
+ const m = cur.members.find((x) => x.name && ts.isIdentifier(x.name) && x.name.text === name);
340
+ if (m)
341
+ return !isAsync(m) && this.throwsInfo.fn(m);
342
+ }
343
+ return false;
324
344
  },
325
345
  /** The memo call (`computed(fn)`) a module-level variable an identifier names is initialized with. */
326
346
  moduleComputed(id) {
@@ -271,6 +271,10 @@ export const constructionMethods = {
271
271
  return `${t}()`;
272
272
  return `${t}(${this.args(e).join(', ')})`;
273
273
  }
274
+ if (this.checker.getTypeAtLocation(callee).getConstructSignatures().length) {
275
+ const made = `NativeScriptKit.jsConstruct(${this.expr(callee)}${this.untypedArgs(e)})`;
276
+ return isUntyped(spelledType(t)) ? made : this.fromAny(made, t);
277
+ }
274
278
  throw this.error(e, 'new');
275
279
  },
276
280
  /** One of the library's error classes, constructed. */