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

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 (181) hide show
  1. package/dist/api/ir.js +7 -1
  2. package/dist/cli/runtime.cjs +7 -1
  3. package/dist/css/css.js +30 -6
  4. package/dist/driver/cli.js +2 -0
  5. package/dist/driver/compile.js +23 -10
  6. package/dist/driver/paths.js +7 -0
  7. package/dist/driver/unimplemented.js +15 -0
  8. package/dist/kotlin/access.js +23 -5
  9. package/dist/kotlin/arguments.js +5 -0
  10. package/dist/kotlin/builtins.js +0 -4
  11. package/dist/kotlin/calls.js +6 -2
  12. package/dist/kotlin/class-methods.js +9 -3
  13. package/dist/kotlin/components.js +13 -8
  14. package/dist/kotlin/conversion.js +17 -5
  15. package/dist/kotlin/core-api.js +2 -13
  16. package/dist/kotlin/declarations.js +2 -0
  17. package/dist/kotlin/expression-statements.js +5 -4
  18. package/dist/kotlin/expressions.js +8 -3
  19. package/dist/kotlin/functions.js +13 -4
  20. package/dist/kotlin/global-calls.js +11 -0
  21. package/dist/kotlin/literals.js +58 -14
  22. package/dist/kotlin/names.js +2 -2
  23. package/dist/kotlin/native/api.js +9 -1
  24. package/dist/kotlin/native/calls.js +84 -3
  25. package/dist/kotlin/native/subclasses.js +4 -3
  26. package/dist/kotlin/native/types.js +8 -5
  27. package/dist/kotlin/operators.js +4 -1
  28. package/dist/kotlin/overrides.js +7 -5
  29. package/dist/kotlin/placement.js +3 -1
  30. package/dist/kotlin/prototype-calls.js +5 -0
  31. package/dist/kotlin/render.js +62 -0
  32. package/dist/kotlin/statements.js +9 -0
  33. package/dist/kotlin/static-calls.js +10 -7
  34. package/dist/kotlin/translator.js +31 -11
  35. package/dist/kotlin/type-facts.js +10 -2
  36. package/dist/kotlin/types.js +6 -6
  37. package/dist/plugins/native-android.js +37 -5
  38. package/dist/plugins/native-ios.js +2 -0
  39. package/dist/plugins/source.js +73 -23
  40. package/dist/program/app-modules.js +91 -16
  41. package/dist/program/app-paths.js +80 -12
  42. package/dist/program/class-mixins.js +463 -0
  43. package/dist/program/core-facts.js +7 -0
  44. package/dist/program/glob.js +274 -0
  45. package/dist/program/platform.js +32 -4
  46. package/dist/program/program.js +239 -38
  47. package/dist/program/source-lines.js +4 -1
  48. package/dist/program/vite-plugins.js +144 -0
  49. package/dist/semantics/apis/globals.js +2 -2
  50. package/dist/semantics/apis/object.js +1 -0
  51. package/dist/semantics/apis/statics.js +6 -0
  52. package/dist/semantics/ast.js +20 -2
  53. package/dist/semantics/classes.js +36 -1
  54. package/dist/semantics/facts.js +28 -1
  55. package/dist/semantics/globals.js +3 -0
  56. package/dist/semantics/lang.js +13 -1
  57. package/dist/semantics/nullish.js +29 -11
  58. package/dist/semantics/refuse-receivers.js +3 -3
  59. package/dist/semantics/refuse-scope.js +2 -7
  60. package/dist/semantics/runtime.js +1 -0
  61. package/dist/semantics/shapes.js +21 -1
  62. package/dist/semantics/states/value-states.js +1 -1
  63. package/dist/semantics/throws.js +1 -0
  64. package/dist/semantics/translator-methods.js +1 -1
  65. package/dist/semantics/types.js +21 -1
  66. package/dist/swift/access.js +25 -10
  67. package/dist/swift/arguments.js +10 -2
  68. package/dist/swift/assignment.js +12 -1
  69. package/dist/swift/builtins.js +0 -4
  70. package/dist/swift/calls.js +6 -2
  71. package/dist/swift/class-methods.js +3 -3
  72. package/dist/swift/components.js +28 -8
  73. package/dist/swift/construction.js +4 -0
  74. package/dist/swift/conversion.js +1 -1
  75. package/dist/swift/core-api.js +9 -12
  76. package/dist/swift/from-any.js +2 -2
  77. package/dist/swift/functions.js +13 -2
  78. package/dist/swift/generics.js +5 -1
  79. package/dist/swift/global-calls.js +2 -0
  80. package/dist/swift/literals.js +57 -10
  81. package/dist/swift/modules.js +1 -1
  82. package/dist/swift/names.js +1 -1
  83. package/dist/swift/native/sdk-tables.js +52 -4
  84. package/dist/swift/native/sdk.js +9 -1
  85. package/dist/swift/operators.js +4 -1
  86. package/dist/swift/parameters.js +5 -2
  87. package/dist/swift/placement.js +44 -4
  88. package/dist/swift/prototype-calls.js +17 -2
  89. package/dist/swift/render.js +64 -0
  90. package/dist/swift/results.js +1 -1
  91. package/dist/swift/statements.js +9 -0
  92. package/dist/swift/static-calls.js +13 -6
  93. package/dist/swift/types.js +9 -9
  94. package/dist/targets/android/build.js +18 -12
  95. package/dist/targets/ios/build.js +11 -10
  96. package/dist/targets/ios/dependencies.js +12 -0
  97. package/dist/targets/resources.js +15 -1
  98. package/dist/template/plan.js +105 -8
  99. package/dist/types/adapter-api.d.ts +13 -0
  100. package/dist/types/ir.d.ts +47 -0
  101. package/kit-android/generated/kotlin/org/nativescript/kit/__Objects.kt +102 -7485
  102. package/kit-android/generated/kotlin/org/nativescript/kit/application_application.kt +4 -4
  103. package/kit-android/generated/kotlin/org/nativescript/kit/image_source_index.kt +1 -1
  104. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_animation_common.kt +7 -3
  105. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_index.kt +3 -1
  106. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_base_index.kt +2 -4
  107. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_index.kt +5 -6
  108. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -3
  109. package/kit-android/generated/kotlin/org/nativescript/kit/ui_dialogs_index.kt +11 -6
  110. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_fragment_transitions.kt +1 -1
  111. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_common.kt +1 -1
  112. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_helper_for_android.kt +7 -5
  113. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_index.kt +6 -3
  114. package/kit-android/generated/kotlin/org/nativescript/kit/ui_gestures_touch_manager.kt +1 -1
  115. package/kit-android/generated/kotlin/org/nativescript/kit/ui_layouts_flexbox_layout_index.kt +1 -1
  116. package/kit-android/generated/kotlin/org/nativescript/kit/ui_search_bar_index.kt +4 -3
  117. package/kit-android/generated/kotlin/org/nativescript/kit/ui_segmented_bar_index.kt +2 -2
  118. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +1 -3
  119. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_index.kt +1 -1
  120. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_fade_transition.kt +1 -1
  121. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_flip_transition.kt +8 -8
  122. package/kit-android/generated/kotlin/org/nativescript/kit/utils_index.kt +1 -1
  123. package/kit-android/generated/source-lines.json +1 -1
  124. package/kit-android/gradlew.bat +94 -0
  125. package/kit-android/src/fromcore/kotlin/org/nativescript/kit/CoreBridge.kt +67 -1
  126. package/kit-android/src/main/kotlin/org/nativescript/kit/Signals.kt +15 -2
  127. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +26 -0
  128. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +4 -4
  129. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +26 -161
  130. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +9 -284
  131. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +11 -7
  132. package/kit-apple/Sources/NativeScriptKit/Core/Object_callback_thisArg_once.swift +1 -1
  133. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_index_section_view_ios_android.swift +7 -5
  134. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_oldIndex_newIndex.swift +4 -2
  135. 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
  136. package/kit-apple/Sources/NativeScriptKit/Core/__Namespace.Utils.swift +17 -15
  137. package/kit-apple/Sources/NativeScriptKit/Core/application-settings.index.ios.swift +8 -8
  138. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +4 -4
  139. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +7 -7
  140. package/kit-apple/Sources/NativeScriptKit/Core/data.observable.index.swift +3 -3
  141. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.index.ios.swift +2 -1
  142. package/kit-apple/Sources/NativeScriptKit/Core/image-source.index.ios.swift +1 -1
  143. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +40 -246
  144. package/kit-apple/Sources/NativeScriptKit/Core/manifest.json +1 -2
  145. package/kit-apple/Sources/NativeScriptKit/Core/ui.action-bar.index.ios.swift +3 -3
  146. package/kit-apple/Sources/NativeScriptKit/Core/ui.button.index.ios.swift +4 -4
  147. package/kit-apple/Sources/NativeScriptKit/Core/ui.content-view.index.swift +8 -8
  148. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +4 -4
  149. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.index.ios.swift +8 -8
  150. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-common.swift +1 -3
  151. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-helper.view-helper-common.swift +7 -7
  152. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.weak-event-listener.index.swift +3 -3
  153. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.index.ios.swift +4 -4
  154. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.index.ios.swift +2 -2
  155. package/kit-apple/Sources/NativeScriptKit/Core/ui.html-view.index.ios.swift +4 -4
  156. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.image-common.swift +2 -2
  157. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.index.ios.swift +4 -4
  158. package/kit-apple/Sources/NativeScriptKit/Core/ui.label.index.ios.swift +4 -4
  159. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.absolute-layout.index.ios.swift +4 -4
  160. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.dock-layout.index.ios.swift +4 -4
  161. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.flexbox-layout.index.ios.swift +3 -3
  162. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.grid-layout.index.ios.swift +4 -4
  163. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.stack-layout.index.ios.swift +4 -4
  164. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.wrap-layout.index.ios.swift +4 -4
  165. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +3 -3
  166. package/kit-apple/Sources/NativeScriptKit/Core/ui.page.index.ios.swift +4 -4
  167. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +10 -6
  168. package/kit-apple/Sources/NativeScriptKit/Core/ui.scroll-view.index.ios.swift +4 -4
  169. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.index.ios.swift +4 -4
  170. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.background.ios.swift +1 -1
  171. package/kit-apple/Sources/NativeScriptKit/Core/ui.tab-view.index.ios.swift +4 -4
  172. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.formatted-string.swift +2 -1
  173. package/kit-apple/Sources/NativeScriptKit/Core/utils.common.swift +9 -9
  174. package/kit-apple/Sources/NativeScriptKit/Core/utils.layout-helper.index.ios.swift +10 -10
  175. package/kit-apple/Sources/NativeScriptKit/CoreBridge.swift +67 -1
  176. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +4 -0
  177. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +25 -0
  178. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +6 -0
  179. package/kit-apple/Sources/NativeScriptKit/Signals.swift +20 -2
  180. package/package.json +2 -1
  181. package/kit-apple/Sources/NativeScriptKit/Core/Object_toString_charAt_charCodeAt_concat_indexOf_lastIndexOf_and_44_more_fc25df.swift +0 -481
@@ -1,5 +1,13 @@
1
1
  // Syntax-tree questions both backends ask, answered the same way for each.
2
2
  import ts from 'typescript';
3
+ /** A constructor body's statements excluding any bare `super(...)` call expression statement. */
4
+ export function nonSuperStatements(ctor) {
5
+ return (ctor?.body?.statements ?? []).filter((s) => !(ts.isExpressionStatement(s) && ts.isCallExpression(s.expression) && s.expression.expression.kind === ts.SyntaxKind.SuperKeyword));
6
+ }
7
+ /** The `extends` heritage entry of a class, if any. */
8
+ export function extendsHeritage(cls) {
9
+ return cls.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
10
+ }
3
11
  /**
4
12
  * `o.k = (o = other)`, `o.k += (o = other).k`: an assignment to a member of the variable `o` whose value assigns `o`.
5
13
  * Script evaluates the target's object before the value, so the member is written on the object `o` held first.
@@ -267,9 +275,9 @@ export function declaresThis(fn) {
267
275
  const first = fn.parameters[0];
268
276
  return !!first && ts.isIdentifier(first.name) && first.name.text === 'this' && first.type?.kind !== ts.SyntaxKind.VoidKeyword;
269
277
  }
270
- /** A function type or function expression declaring its `this` with a type other than void. */
278
+ /** A function type, function expression or method signature declaring its `this` with a type other than void. */
271
279
  export function takesOwnThis(d) {
272
- return !!d && (ts.isFunctionTypeNode(d) || ts.isFunctionExpression(d)) && d.parameters.some((q) => ts.isIdentifier(q.name) && q.name.text === 'this' && !!q.type && q.type.kind !== ts.SyntaxKind.VoidKeyword);
280
+ return !!d && (ts.isFunctionTypeNode(d) || ts.isFunctionExpression(d) || ts.isMethodSignature(d)) && d.parameters.some((q) => ts.isIdentifier(q.name) && q.name.text === 'this' && !!q.type && q.type.kind !== ts.SyntaxKind.VoidKeyword);
273
281
  }
274
282
  /** Whether `this` appears in `e` outside nested functions, methods and classes, which bind their own. */
275
283
  export function refersToThis(e) {
@@ -313,3 +321,13 @@ export function notIterable(e) {
313
321
  const x = ts.skipOuterExpressions(e);
314
322
  return ts.isCallExpression(x) ? `${v8Text(x.expression)} is not a function or its return value is not iterable` : `${v8Text(x)} is not iterable`;
315
323
  }
324
+ /** The `length` property's value expression in `Array.from({ length }, fn)` / `Array.from({ length: n }, fn)`, if present. */
325
+ export function arrayFromLengthInit(obj) {
326
+ const length = obj.properties.find((p) => p.name?.getText() === 'length');
327
+ return length && (ts.isPropertyAssignment(length) ? length.initializer : ts.isShorthandPropertyAssignment(length) ? length.name : undefined);
328
+ }
329
+ /** The element types of a spread expression `...x` when `x` is a fixed tuple type; null otherwise. */
330
+ export function tupleSpreadTypes(x, checker) {
331
+ const st = checker.getNonNullableType(checker.getTypeAtLocation(x.expression));
332
+ return checker.isTupleType(st) ? checker.getTypeArguments(st) : null;
333
+ }
@@ -1,9 +1,44 @@
1
1
  // A class's place in its hierarchy, as the checker gives it: its program base, the constructor it runs, what it inherits.
2
2
  import ts from 'typescript';
3
- import { ERRORS } from "./globals.js";
3
+ import { ERRORS, isLibGlobal } from "./globals.js";
4
4
  import { isStatic } from "./throws.js";
5
5
  import { hasModifier, isLibDeclaration, isWriteTarget } from "./ast.js";
6
6
  import { literalKey, optionalBodilessMethod } from "./lang.js";
7
+ /** The program class declaring `static [Symbol.hasInstance]`, if `e` names one. */
8
+ export function hasInstanceClass(e, checker) {
9
+ if (!ts.isIdentifier(e) && !ts.isPropertyAccessExpression(e))
10
+ return null;
11
+ let sym = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(e) ? e.name : e);
12
+ if (sym && sym.flags & ts.SymbolFlags.Alias)
13
+ sym = checker.getAliasedSymbol(sym);
14
+ const decl = sym?.valueDeclaration;
15
+ if (!decl || !ts.isClassDeclaration(decl) || decl.getSourceFile().isDeclarationFile)
16
+ return null;
17
+ for (let c = decl; c; c = programBase(c, checker)) {
18
+ if (c.members.some((m) => ts.isMethodDeclaration(m) &&
19
+ !!m.body &&
20
+ isStatic(m) &&
21
+ ts.isComputedPropertyName(m.name) &&
22
+ ts.isPropertyAccessExpression(m.name.expression) &&
23
+ ts.isIdentifier(m.name.expression.expression) &&
24
+ m.name.expression.expression.text === 'Symbol' &&
25
+ m.name.expression.name.text === 'hasInstance'))
26
+ return decl;
27
+ }
28
+ return null;
29
+ }
30
+ /** A member declared on a class applied as a mixin: the extension it becomes has it by name. */
31
+ export function isMixinOwnMember(name, checker, mixinOf) {
32
+ const decl = checker.getSymbolAtLocation(name)?.valueDeclaration;
33
+ return !!decl && ts.isClassDeclaration(decl.parent) && !!mixinOf(checker.getSymbolAtLocation(decl.parent.name));
34
+ }
35
+ /** The class symbol whose `.prototype` is read (`Cls.prototype`), excluding ES lib globals. */
36
+ export function prototypeClassSymbol(target, name, b) {
37
+ if (name !== 'prototype' || (ts.isIdentifier(target) && isLibGlobal(b, target)))
38
+ return null;
39
+ const sym = b.resolve(target);
40
+ return sym && sym.flags & ts.SymbolFlags.Class ? sym : null;
41
+ }
7
42
  /** The class `cls` extends where the program's own source declares it; undefined for a library's class or none. */
8
43
  export function programBase(cls, checker) {
9
44
  const h = cls.heritageClauses?.find((x) => x.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
@@ -4,7 +4,7 @@
4
4
  import ts from 'typescript';
5
5
  import { definitelyAssignedFields, isArguments, classesHeldUntyped } from "./lang.js";
6
6
  import { baseMethod, declaringMethod, literalClassOf, programBase, rootMethod, shapesClassOf } from "./classes.js";
7
- import { expandoRootsOf, instanceKeysOf } from "./shapes.js";
7
+ import { expandoRootsOf, instanceKeysOf, isShapeInterfaceDecl } from "./shapes.js";
8
8
  import { hasModifier, resolveSymbol } from "./ast.js";
9
9
  import { isStatic } from "./throws.js";
10
10
  import { assignedMembers } from "./sharing.js";
@@ -38,6 +38,33 @@ export class ProgramFacts {
38
38
  familyMap = null;
39
39
  protoKeys = null;
40
40
  tdzSet = null;
41
+ ifaceDecls = null;
42
+ ifaceNamesByTop = new WeakMap();
43
+ /** All interface / object-shape type alias declarations across the program's source files. */
44
+ interfaceDecls() {
45
+ if (this.ifaceDecls)
46
+ return this.ifaceDecls;
47
+ const out = [];
48
+ const visit = (n) => {
49
+ if (isShapeInterfaceDecl(n))
50
+ out.push(n);
51
+ ts.forEachChild(n, visit);
52
+ };
53
+ for (const f of this.files)
54
+ visit(f);
55
+ return (this.ifaceDecls = out);
56
+ }
57
+ /** Whether `name` is an interface registered in `interfaces` or declared anywhere in `this.files` under `owner`'s top-level naming. */
58
+ hasInterface(owner, interfaces, topName, name) {
59
+ if (interfaces.has(name))
60
+ return true;
61
+ let set = this.ifaceNamesByTop.get(owner);
62
+ if (!set) {
63
+ set = new Set(this.interfaceDecls().map((n) => topName(n, n.name.text)));
64
+ this.ifaceNamesByTop.set(owner, set);
65
+ }
66
+ return set.has(name);
67
+ }
41
68
  checker;
42
69
  files;
43
70
  scope;
@@ -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',
@@ -1,5 +1,5 @@
1
1
  import ts from 'typescript';
2
- import { heldOf, isPrimitive, presentOf, spelledType } from "./types.js";
2
+ import { heldOf, isPrimitive, isUntyped, presentOf, spelledType } from "./types.js";
3
3
  import { admitsUndefined, alwaysThrows, containsThis, hasStatic, jsKeyOrder, literalKey, onlyUndefined } from "./lang.js";
4
4
  import { programBase } from "./classes.js";
5
5
  import { assignsClassFields } from "./class-plan.js";
@@ -39,6 +39,18 @@ export function inPlanOrder(plan, fields) {
39
39
  }
40
40
  /** The type holds nil as its value: `T?`, `Any?`. */
41
41
  export const holdsNil = (h) => h === 'optional' || h === 'any';
42
+ /** An interface or object-shape type alias declared in program source (collected upfront for order-independent checks). */
43
+ export const isShapeInterfaceDecl = (n) => !n.getSourceFile().isDeclarationFile && (ts.isInterfaceDeclaration(n) || (ts.isTypeAliasDeclaration(n) && (ts.isTypeLiteralNode(n.type) || ts.isIntersectionTypeNode(n.type))));
44
+ /** Property access inside `Array.isArray(x)` when `x` reads a property off an object shape / interface view. */
45
+ export function shapeArrayGuardAccess(arg, isShape, typeOf) {
46
+ const a0 = arg ? ts.skipParentheses(arg) : undefined;
47
+ if (!a0 || !ts.isPropertyAccessExpression(a0))
48
+ return null;
49
+ const recvType = typeOf(a0.expression);
50
+ if (!isShape(recvType.replace(/[?!]$/, '')))
51
+ return null;
52
+ return { prop: a0, optional: !!a0.questionDotToken || recvType.endsWith('?') };
53
+ }
42
54
  /** The spelling ends in `?`, a function's result's included. */
43
55
  export const spelledOptional = (h) => holdsNil(h) || h === 'optional-result';
44
56
  /** The type holds nil, implicitly unwrapped or not. */
@@ -658,3 +670,11 @@ function runsCode(n, deep = true) {
658
670
  visit(n);
659
671
  return found;
660
672
  }
673
+ /** Whether spreading elements of `from` into an array of `to` requires elementwise mapping (untyped source or distinct structural shapes). */
674
+ export function spreadElementNeedsMap(from, to, isShape, mapUntyped) {
675
+ if (from === to)
676
+ return false;
677
+ if (mapUntyped && isUntyped(spelledType(from)))
678
+ return true;
679
+ return !isUntyped(spelledType(to)) && isShape(to.replace(/\?$/, '')) && isShape(from.replace(/\?$/, ''));
680
+ }
@@ -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.