@nstudio/nativescript-compiler 9.2.0-alpha.17 → 9.2.0-alpha.18

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 (162) hide show
  1. package/README.md +3 -0
  2. package/dist/kotlin/access.js +8 -7
  3. package/dist/kotlin/assignment.js +22 -13
  4. package/dist/kotlin/builtins.js +67 -0
  5. package/dist/kotlin/calls.js +3 -2
  6. package/dist/kotlin/class-declaration.js +4 -9
  7. package/dist/kotlin/class-methods.js +2 -2
  8. package/dist/kotlin/core-api.js +1 -1
  9. package/dist/kotlin/declarations.js +1 -1
  10. package/dist/kotlin/expression-statements.js +13 -1
  11. package/dist/kotlin/functions.js +1 -0
  12. package/dist/kotlin/literals.js +4 -8
  13. package/dist/kotlin/names.js +4 -4
  14. package/dist/kotlin/native/api.js +1 -1
  15. package/dist/kotlin/operators.js +25 -25
  16. package/dist/kotlin/optional-chains.js +1 -1
  17. package/dist/kotlin/overrides.js +2 -2
  18. package/dist/kotlin/state-backend.js +6 -2
  19. package/dist/kotlin/translator.js +1 -1
  20. package/dist/kotlin/types.js +4 -4
  21. package/dist/semantics/classes.js +15 -0
  22. package/dist/semantics/facts.js +1 -1
  23. package/dist/semantics/lang.js +10 -0
  24. package/dist/semantics/lower.js +54 -0
  25. package/dist/semantics/lowering-methods.js +5 -0
  26. package/dist/semantics/placement.js +9 -3
  27. package/dist/semantics/signals.js +11 -0
  28. package/dist/semantics/states/missing.js +7 -0
  29. package/dist/semantics/tdz.js +54 -15
  30. package/dist/semantics/throws.js +1 -1
  31. package/dist/semantics/translator-methods.js +1 -1
  32. package/dist/swift/access.js +7 -9
  33. package/dist/swift/assignment.js +20 -14
  34. package/dist/swift/calls.js +6 -3
  35. package/dist/swift/classes.js +7 -9
  36. package/dist/swift/components.js +3 -3
  37. package/dist/swift/control-flow.js +1 -1
  38. package/dist/swift/conversion.js +5 -2
  39. package/dist/swift/core-api.js +2 -2
  40. package/dist/swift/declarations.js +1 -1
  41. package/dist/swift/expressions.js +6 -2
  42. package/dist/swift/from-any.js +1 -1
  43. package/dist/swift/functions.js +5 -6
  44. package/dist/swift/global-calls.js +1 -1
  45. package/dist/swift/lenient.js +1 -6
  46. package/dist/swift/literals.js +8 -3
  47. package/dist/swift/modules.js +3 -3
  48. package/dist/swift/names.js +3 -3
  49. package/dist/swift/native/calls.js +1 -1
  50. package/dist/swift/object-classes.js +84 -1
  51. package/dist/swift/operators.js +31 -29
  52. package/dist/swift/placement.js +4 -3
  53. package/dist/swift/state-backend.js +3 -2
  54. package/dist/swift/static-calls.js +2 -3
  55. package/dist/swift/syntax.js +9 -5
  56. package/dist/swift/translator.js +1 -1
  57. package/dist/swift/type-facts.js +3 -3
  58. package/dist/swift/types.js +3 -3
  59. package/dist/targets/ios/build.js +1 -1
  60. package/kit-android/generated/kotlin/org/nativescript/kit/__Modules.kt +1 -0
  61. package/kit-android/generated/kotlin/org/nativescript/kit/__Objects.kt +525 -99
  62. package/kit-android/generated/kotlin/org/nativescript/kit/accessibility_accessibility_common.kt +2 -2
  63. package/kit-android/generated/kotlin/org/nativescript/kit/application_application_common.kt +29 -6
  64. package/kit-android/generated/kotlin/org/nativescript/kit/application_helpers_common.kt +14 -0
  65. package/kit-android/generated/kotlin/org/nativescript/kit/color_color_utils.kt +3 -3
  66. package/kit-android/generated/kotlin/org/nativescript/kit/css_mediaquery_index.kt +49 -1
  67. package/kit-android/generated/kotlin/org/nativescript/kit/data_observable_array_index.kt +0 -8
  68. package/kit-android/generated/kotlin/org/nativescript/kit/data_observable_index.kt +0 -16
  69. package/kit-android/generated/kotlin/org/nativescript/kit/data_virtual_array_index.kt +6 -4
  70. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_index.kt +19 -7
  71. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_http_request_internal_common.kt +14 -0
  72. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_index.kt +19 -10
  73. package/kit-android/generated/kotlin/org/nativescript/kit/matrix_index.kt +17 -29
  74. package/kit-android/generated/kotlin/org/nativescript/kit/media_query_list_index.kt +144 -22
  75. package/kit-android/generated/kotlin/org/nativescript/kit/npm_css_what_src_parse.kt +8 -3
  76. package/kit-android/generated/kotlin/org/nativescript/kit/org.nativescript.NativeScriptLifecycleCallbacks.kt +2 -10
  77. package/kit-android/generated/kotlin/org/nativescript/kit/ui_builder_index.kt +0 -2
  78. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_bindable_expression_parser.kt +6 -10
  79. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +531 -8
  80. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_base_index.kt +0 -9
  81. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_weak_event_listener_index.kt +3 -3
  82. package/kit-android/generated/kotlin/org/nativescript/kit/ui_styling_style_index.kt +19 -0
  83. package/kit-android/generated/kotlin/org/nativescript/kit/ui_styling_style_properties.kt +5 -2
  84. package/kit-android/generated/kotlin/org/nativescript/kit/ui_styling_style_scope.kt +232 -174
  85. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_view_text_view_common.kt +1 -1
  86. package/kit-android/generated/kotlin/org/nativescript/kit/utils_android_runtime_version.kt +75 -0
  87. package/kit-android/generated/manifest.json +21 -18
  88. package/kit-android/generated/source-lines.json +1 -1
  89. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Array.kt +497 -42
  90. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Intl.kt +1 -1
  91. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/JSON.kt +22 -2
  92. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Strings.kt +32 -18
  93. package/kit-apple/Overlays/xml-free/Core/ui.builder.index.swift +1 -1
  94. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +14 -10
  95. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +3 -9
  96. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +20 -21
  97. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_index_section_view_ios_android.swift +5 -7
  98. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_ios_android_.swift +130 -0
  99. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_oldIndex_newIndex.swift +2 -4
  100. package/kit-apple/Sources/NativeScriptKit/Core/Object_specified_substituted_reads.swift +115 -0
  101. package/kit-apple/Sources/NativeScriptKit/Core/Object_substituted_values_reads.swift +113 -0
  102. package/kit-apple/Sources/NativeScriptKit/Core/Object_substituted_values_reads_.swift +113 -0
  103. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +348 -330
  104. package/kit-apple/Sources/NativeScriptKit/Core/application.application.ios.swift +358 -359
  105. package/kit-apple/Sources/NativeScriptKit/Core/application.helpers-common.swift +47 -29
  106. package/kit-apple/Sources/NativeScriptKit/Core/connectivity.index.ios.swift +3 -1
  107. package/kit-apple/Sources/NativeScriptKit/Core/css-mediaquery.index.swift +95 -53
  108. package/kit-apple/Sources/NativeScriptKit/Core/css.CSS3Parser.swift +1 -1
  109. package/kit-apple/Sources/NativeScriptKit/Core/css.parser.swift +1 -1
  110. package/kit-apple/Sources/NativeScriptKit/Core/data.observable-array.index.swift +2 -2
  111. package/kit-apple/Sources/NativeScriptKit/Core/file-system.file-system-access.ios.swift +52 -43
  112. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.http-request-internal-common.swift +18 -0
  113. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.index.ios.swift +66 -51
  114. package/kit-apple/Sources/NativeScriptKit/Core/image-source.index.ios.swift +67 -51
  115. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +143 -32
  116. package/kit-apple/Sources/NativeScriptKit/Core/manifest.json +30 -19
  117. package/kit-apple/Sources/NativeScriptKit/Core/media-query-list.index.swift +190 -78
  118. package/kit-apple/Sources/NativeScriptKit/Core/native-window.native-window.ios.swift +1 -1
  119. package/kit-apple/Sources/NativeScriptKit/Core/npm.css-what.src.parse.swift +205 -201
  120. package/kit-apple/Sources/NativeScriptKit/Core/npm.css-what.src.stringify.swift +41 -42
  121. package/kit-apple/Sources/NativeScriptKit/Core/npm.css-what.src.types.swift +1 -1
  122. package/kit-apple/Sources/NativeScriptKit/Core/trace.index.swift +2 -2
  123. package/kit-apple/Sources/NativeScriptKit/Core/ui.animation.index.ios.swift +77 -65
  124. package/kit-apple/Sources/NativeScriptKit/Core/ui.builder.index.swift +4 -4
  125. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.properties.index.swift +1272 -824
  126. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +2 -2
  127. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.index.ios.swift +8 -8
  128. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-common.swift +1 -1
  129. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.frame-common.swift +2 -1
  130. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.index.ios.swift +6 -6
  131. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.flexbox-layout.index.ios.swift +22 -21
  132. package/kit-apple/Sources/NativeScriptKit/Core/ui.page.index.ios.swift +202 -188
  133. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +2 -6
  134. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.index.ios.swift +3 -3
  135. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.background.ios.swift +2 -2
  136. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.clip-path-function.swift +1 -1
  137. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-animation-parser.swift +1 -1
  138. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +2 -2
  139. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.font-common.swift +2 -2
  140. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.style-scope.swift +869 -838
  141. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.style.index.swift +46 -31
  142. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.formatted-string.swift +1 -2
  143. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-view.text-view-common.swift +1 -1
  144. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.index.ios.swift +2 -2
  145. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.modal-transition.ios.swift +4 -4
  146. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.page-transition.ios.swift +2 -2
  147. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.shared-transition-helper.ios.swift +17 -17
  148. package/kit-apple/Sources/NativeScriptKit/Core/utils.android-runtime-version.swift +77 -0
  149. package/kit-apple/Sources/NativeScriptKit/Core/utils.debug-source.swift +2 -2
  150. package/kit-apple/Sources/NativeScriptKit/Core/xhr.index.swift +62 -61
  151. package/kit-apple/Sources/NativeScriptKit/Runtime/Array.swift +4 -0
  152. package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +2 -0
  153. package/kit-apple/Sources/NativeScriptKit/Runtime/Interop.swift +1 -1
  154. package/kit-apple/Sources/NativeScriptKit/Runtime/Intl.swift +1 -1
  155. package/kit-apple/Sources/NativeScriptKit/Runtime/Iterators.swift +1 -1
  156. package/kit-apple/Sources/NativeScriptKit/Runtime/JSON.swift +280 -9
  157. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +3 -2
  158. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +1 -0
  159. package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +1 -0
  160. package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +1 -0
  161. package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +2 -0
  162. package/package.json +2 -2
@@ -619,3 +619,18 @@ export function spellInstantiatedCollection(type, checker, render) {
619
619
  const args = info.typeArgs.map(render);
620
620
  return info.kind === 'Map' ? `JSMap<${args[0] ?? 'Any?'}, ${args[1] ?? 'Any?'}>` : `JS${info.kind}<${args[0] ?? 'Any?'}>`;
621
621
  }
622
+ /** Own instance methods of `cls` eligible for non-enumerable registration on `JSPrototypes.of(...)`. */
623
+ export function prototypeMethodList(cls, options) {
624
+ const seen = new Set();
625
+ const out = [];
626
+ for (const m of cls.members) {
627
+ if (!ts.isMethodDeclaration(m) || !m.body || isStatic(m) || ts.isPrivateIdentifier(m.name) || ts.isComputedPropertyName(m.name) || m.typeParameters?.length || m.asteriskToken)
628
+ continue;
629
+ const key = m.name.getText().replace(/^['"]|['"]$/g, '');
630
+ if (seen.has(key) || options.skip(m, key))
631
+ continue;
632
+ seen.add(key);
633
+ out.push({ method: m, key });
634
+ }
635
+ return out;
636
+ }
@@ -47,7 +47,7 @@ export class ProgramFacts {
47
47
  return this.ifaceDecls;
48
48
  const out = [];
49
49
  const visit = (n) => {
50
- if (isShapeInterfaceDecl(n))
50
+ if (isShapeInterfaceDecl(n) && !(this.checker.getSymbolAtLocation(n.name)?.flags & ts.SymbolFlags.Class))
51
51
  out.push(n);
52
52
  ts.forEachChild(n, visit);
53
53
  };
@@ -281,3 +281,13 @@ export function untypedVariableInitializer(n, resolve) {
281
281
  const d = ts.isVariableDeclaration(n) ? n : ts.isIdentifier(n) ? (ts.isVariableDeclaration(n.parent) && n.parent.name === n ? n.parent : resolve(n)?.valueDeclaration) : undefined;
282
282
  return d && ts.isVariableDeclaration(d) && !d.type && d.initializer ? ts.skipOuterExpressions(d.initializer, ts.OuterExpressionKinds.Parentheses) : null;
283
283
  }
284
+ /** Whether a built-in primitive constructor value (`Number`, `String`, `Boolean`) is a singleton constructor reference (`jsNumberConstructor`) or a typed converter slot. */
285
+ export function builtinConstructorSlot(e, checker, isUntypedContext) {
286
+ const context = checker.getContextualType(e);
287
+ const slot = context && checker.getNonNullableType(context).getCallSignatures()[0];
288
+ if (slot)
289
+ return { slot };
290
+ const p = e.parent;
291
+ const untyped = (!!context && isUntypedContext(context)) || (ts.isBinaryExpression(p) && [ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken].includes(p.operatorToken.kind));
292
+ return untyped ? { singleton: `js${e.text}Constructor` } : {};
293
+ }
@@ -88,3 +88,57 @@ export function flattenStringConcat(expr, isString) {
88
88
  visit(expr);
89
89
  return out;
90
90
  }
91
+ /** Classifies `===`, `!==`, `==`, `!=` into nullish comparison, dynamic runtime helper, or direct backend comparison. */
92
+ export function planEquality(op, leftAny, rightAny, leftNullish, rightNullish) {
93
+ let kind;
94
+ let negated;
95
+ switch (op) {
96
+ case K.EqualsEqualsEqualsToken:
97
+ kind = 'strict';
98
+ negated = false;
99
+ break;
100
+ case K.ExclamationEqualsEqualsToken:
101
+ kind = 'strict';
102
+ negated = true;
103
+ break;
104
+ case K.EqualsEqualsToken:
105
+ kind = 'loose';
106
+ negated = false;
107
+ break;
108
+ case K.ExclamationEqualsToken:
109
+ kind = 'loose';
110
+ negated = true;
111
+ break;
112
+ default:
113
+ return null;
114
+ }
115
+ if (leftNullish || rightNullish)
116
+ return { kind, negated, mode: 'nullish' };
117
+ if (leftAny || rightAny || kind === 'loose')
118
+ return { kind, negated, mode: 'dynamic' };
119
+ return { kind, negated, mode: 'direct' };
120
+ }
121
+ /** Classifies `a ?? b` based on whether the left operand is untyped, optional, or statically present. */
122
+ export function planNullishCoalesce(leftAny, leftOptional) {
123
+ if (leftAny)
124
+ return { kind: 'dynamic' };
125
+ if (leftOptional)
126
+ return { kind: 'optional' };
127
+ return { kind: 'identity' };
128
+ }
129
+ /** Extracts `typeof x === 'tag'` (or `!==`, `==`, `!=`, in either operand order) into a backend-neutral descriptor. */
130
+ export function typeofComparison(e) {
131
+ const op = e.operatorToken.kind;
132
+ const strict = op === K.EqualsEqualsEqualsToken || op === K.ExclamationEqualsEqualsToken;
133
+ const loose = op === K.EqualsEqualsToken || op === K.ExclamationEqualsToken;
134
+ if (!strict && !loose)
135
+ return null;
136
+ const negated = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
137
+ const left = ts.skipParentheses(e.left);
138
+ const right = ts.skipParentheses(e.right);
139
+ if (ts.isTypeOfExpression(left) && ts.isStringLiteralLike(right))
140
+ return { operand: left.expression, tag: right.text, negated, strict };
141
+ if (ts.isTypeOfExpression(right) && ts.isStringLiteralLike(left))
142
+ return { operand: right.expression, tag: left.text, negated, strict };
143
+ return null;
144
+ }
@@ -207,4 +207,9 @@ export const loweringMethods = {
207
207
  }
208
208
  }
209
209
  },
210
+ /** Refuses a self-referencing named generator expression (`function* f() { yield f; }`). */
211
+ refuseNamedGenerator(fn) {
212
+ if (fn.asteriskToken)
213
+ throw this.error(fn, 'a named function expression', 'named-function-expression');
214
+ },
210
215
  };
@@ -107,7 +107,7 @@ function placed(b, e, target, slot) {
107
107
  throw b.error(e, rule.refuse);
108
108
  // `readHeld` derives the carrier of a name or member read only; any other read's code converts itself.
109
109
  const read = ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses);
110
- const code = rule.rule === 'untyped' && (ts.isIdentifier(read) || ts.isPropertyAccessExpression(read)) ? b.untypedRead(b.expr(e), target) : b.coerceTyped(e, target);
110
+ const code = rule.rule === 'untyped' && (ts.isIdentifier(read) || ts.isPropertyAccessExpression(read)) ? b.untypedRead(b.expr(e), target, e) : b.coerceTyped(e, target);
111
111
  // A slot taking a string, number or boolean's undefined, or any value, takes it as it is, not converted.
112
112
  if (takesUndefined(to)) {
113
113
  const held = b.undefinedConverted(code) ?? (choice !== e && !b.library ? b.undefinedConverted(b.coerceTyped(choice, target)) : null);
@@ -564,9 +564,15 @@ export function assertedReceiverCell(b, target, key) {
564
564
  return { cell: 'asIs' };
565
565
  return receiverCell(b, receiverSlot(target, key));
566
566
  }
567
- /** An element read's receiver cell (`assertedReceiverCell`). */
567
+ /** An element read's receiver cell (`assertedReceiverCell` or `unsafeReceiver`). */
568
568
  export function elementReceiverCell(b, e) {
569
- return ts.isOptionalChain(e) ? { cell: 'asIs' } : assertedReceiverCell(b, e.expression, keyName(e.argumentExpression));
569
+ if (ts.isOptionalChain(e))
570
+ return { cell: 'asIs' };
571
+ const key = keyName(e.argumentExpression);
572
+ const asserted = assertedReceiverCell(b, e.expression, key);
573
+ if (asserted.cell !== 'asIs')
574
+ return asserted;
575
+ return unsafeReceiver(e.expression, b.checker) ? receiverCell(b, receiverSlot(e.expression, key)) : { cell: 'asIs' };
570
576
  }
571
577
  /** The name a TypeError reading by `key` gives: a literal key's text, else the key's source. */
572
578
  export function keyName(key) {
@@ -164,3 +164,14 @@ export function propSignal(e, checker, framework) {
164
164
  const kind = name === undefined ? undefined : framework.signalKind(name);
165
165
  return kind === 'input' || kind === 'model';
166
166
  }
167
+ /** Whether `n` declares or references an untyped variable initialized from a read of a signal holding null (`const card = this.morning()`). */
168
+ export function isGivenNullSignalValue(n, resolve, isNullSignalRead) {
169
+ const d = (ts.isVariableDeclaration(n.parent) && n.parent.name === n ? n.parent : ts.isIdentifier(n) ? resolve(n)?.valueDeclaration : undefined);
170
+ if (!d || !ts.isVariableDeclaration(d) || d.type || !d.initializer)
171
+ return false;
172
+ return isNullSignalRead(d.initializer);
173
+ }
174
+ /** Whether a class property declaration initializes a read-only signal via memoization or `.asReadonly()`. */
175
+ export function isReadonlySignalProperty(decl, checker, framework, callee) {
176
+ return !!framework.memoized(decl, checker) || /\.asReadonly$/.test(callee);
177
+ }
@@ -239,6 +239,13 @@ export const missingMethods = {
239
239
  */
240
240
  widenedObject(x) {
241
241
  const results = (e) => {
242
+ if (ts.isAwaitExpression(e)) {
243
+ const inner = ts.skipOuterExpressions(e.expression, ts.OuterExpressionKinds.Parentheses);
244
+ if (!ts.isCallExpression(inner))
245
+ return [];
246
+ const d = this.checker.getResolvedSignature(inner)?.getDeclaration();
247
+ return d && !ts.isJSDocSignature(d) && (this.lenientAsync(d) || !this.appCode(d)) ? [d] : [];
248
+ }
242
249
  if (!ts.isCallExpression(e))
243
250
  return [];
244
251
  const d = this.checker.getResolvedSignature(e)?.getDeclaration();
@@ -51,13 +51,14 @@ function addSameModuleTdz(checker, sf, out) {
51
51
  }
52
52
  if (!decls.size)
53
53
  return;
54
- // Track which statement indices have executable code before them.
55
- const runnableBefore = new Array(sf.statements.length).fill(false);
56
- let ran = false;
57
- for (let i = 0; i < sf.statements.length; i++) {
58
- runnableBefore[i] = ran;
59
- if (canRunCode(sf.statements[i]))
60
- ran = true;
54
+ // Track which hoisted function declarations are reachable from executable statements before each statement index.
55
+ const hoistedFns = new Map();
56
+ for (const st of sf.statements) {
57
+ if (ts.isFunctionDeclaration(st) && st.name && st.body) {
58
+ const sym = checker.getSymbolAtLocation(st.name);
59
+ if (sym)
60
+ hoistedFns.set(sym, st);
61
+ }
61
62
  }
62
63
  const isRef = (n) => {
63
64
  const p = n.parent;
@@ -71,28 +72,66 @@ function addSameModuleTdz(checker, sf, out) {
71
72
  return false;
72
73
  return true;
73
74
  };
74
- const walk = (node, stmtIndex, inHoistedFn, inDeferredScope) => {
75
+ const referencedFnsIn = (root) => {
76
+ const refs = new Set();
77
+ const visit = (n) => {
78
+ if (ts.isIdentifier(n) && isRef(n)) {
79
+ const sym = resolveSymbol(n, checker);
80
+ if (sym && hoistedFns.has(sym))
81
+ refs.add(sym);
82
+ }
83
+ ts.forEachChild(n, visit);
84
+ };
85
+ ts.forEachChild(root, visit);
86
+ return refs;
87
+ };
88
+ const fnCalls = new Map();
89
+ for (const [sym, fn] of hoistedFns)
90
+ fnCalls.set(sym, referencedFnsIn(fn.body));
91
+ const closeReach = (seeds) => {
92
+ const reached = new Set(seeds);
93
+ const queue = [...seeds];
94
+ while (queue.length) {
95
+ const cur = queue.pop();
96
+ for (const next of fnCalls.get(cur) ?? []) {
97
+ if (!reached.has(next)) {
98
+ reached.add(next);
99
+ queue.push(next);
100
+ }
101
+ }
102
+ }
103
+ return reached;
104
+ };
105
+ const reachableFnsBefore = new Array(sf.statements.length);
106
+ const seenBefore = new Set();
107
+ for (let i = 0; i < sf.statements.length; i++) {
108
+ reachableFnsBefore[i] = closeReach(seenBefore);
109
+ const st = sf.statements[i];
110
+ if (!ts.isFunctionDeclaration(st) && canRunCode(st)) {
111
+ for (const s of referencedFnsIn(st))
112
+ seenBefore.add(s);
113
+ }
114
+ }
115
+ const walk = (node, stmtIndex, hoistedSym, inDeferredScope) => {
75
116
  if (ts.isIdentifier(node) && isRef(node)) {
76
117
  const sym = resolveSymbol(node, checker);
77
118
  const entry = sym ? decls.get(sym) : undefined;
78
119
  if (entry) {
79
- const priorExecutable = runnableBefore[entry.stmtIndex] ||
80
- (stmtIndex === entry.stmtIndex &&
81
- ts.isVariableStatement(sf.statements[stmtIndex]) &&
82
- sf.statements[stmtIndex].declarationList.declarations.slice(0, entry.declIndex).some((prev) => !!prev.initializer && exprCanRunCode(prev.initializer)));
83
120
  const beforeDecl = stmtIndex < entry.stmtIndex;
84
121
  const inOwnInit = !inDeferredScope && stmtIndex === entry.stmtIndex && node.pos >= entry.decl.initializer.pos && node.end <= entry.decl.initializer.end;
85
- if ((beforeDecl && (!inDeferredScope || priorExecutable)) || (inHoistedFn && priorExecutable) || inOwnInit) {
122
+ const fnReachableEarly = !!hoistedSym && reachableFnsBefore[entry.stmtIndex].has(hoistedSym);
123
+ if ((beforeDecl && !inDeferredScope) || fnReachableEarly || inOwnInit) {
86
124
  out.add(entry.decl);
87
125
  }
88
126
  }
89
127
  }
90
128
  const entersDeferred = ts.isFunctionLike(node) || ts.isClassStaticBlockDeclaration(node);
91
- ts.forEachChild(node, (child) => walk(child, stmtIndex, inHoistedFn, inDeferredScope || entersDeferred));
129
+ ts.forEachChild(node, (child) => walk(child, stmtIndex, hoistedSym, inDeferredScope || entersDeferred));
92
130
  };
93
131
  for (let i = 0; i < sf.statements.length; i++) {
94
132
  const st = sf.statements[i];
95
- walk(st, i, ts.isFunctionDeclaration(st), false);
133
+ const hoistedSym = ts.isFunctionDeclaration(st) && st.name ? (checker.getSymbolAtLocation(st.name) ?? null) : null;
134
+ walk(st, i, hoistedSym, false);
96
135
  }
97
136
  }
98
137
  /**
@@ -460,7 +460,7 @@ export class Throws {
460
460
  return true;
461
461
  if (ts.isPropertyAccessExpression(n) && !n.questionDotToken && unsafeReceiver(n.expression, c))
462
462
  return true;
463
- if (ts.isElementAccessExpression(n) && !n.questionDotToken && ts.isOptionalChain(n) && unsafeReceiver(n.expression, c))
463
+ if (ts.isElementAccessExpression(n) && !n.questionDotToken && unsafeReceiver(n.expression, c))
464
464
  return true;
465
465
  if ((ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n)) && !n.questionDotToken && uncheckedMatch(n.expression, c))
466
466
  return true;
@@ -548,7 +548,7 @@ export const frontMethods = traceMethods('front', {
548
548
  // JavaScript's assertion converts nothing: an empty value asserted to an array is still empty where it is read.
549
549
  if (isPrimitive(t) || t.kind === 'array')
550
550
  return isUntyped(from) ? e : null;
551
- return isUntyped(from) && this.untypedCastChecks(e, t) ? e : null;
551
+ return isUntyped(from) && this.states.backend.untypedCastChecks(e, t) ? e : null;
552
552
  }
553
553
  catch (err) {
554
554
  rethrowUnlessRefused(err);
@@ -6,7 +6,7 @@ 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
8
  import { ERRORS, isLibGlobal } from "../semantics/globals.js";
9
- import { spell, escapingFunction, functionParts, hasTopLevelArrow, ident, identPath, isFunctionType, isOptional, openSwiftChain, optionalType, splitTopLevel, swiftString, RT, lenientReader } from "./syntax.js";
9
+ import { escapingFunction, functionParts, hasTopLevelArrow, ident, identPath, isFunctionType, isOptional, openSwiftChain, optionalType, splitTopLevel, swiftString, RT, lenientReader } from "./syntax.js";
10
10
  import { elementReceiverCell, keyName, receiverCell, receiverSlot, isEnumObject, nullishField } from "../semantics/placement.js";
11
11
  import { ambientAddedMemberOf, augmentedPropertyRead, functionProperty, uncheckedMatch, wellKnownMember, isSelf } from "../semantics/lang.js";
12
12
  import { convertedRead, onlyNull } from "../semantics/states/predicates.js";
@@ -420,17 +420,19 @@ export const accessMethods = {
420
420
  },
421
421
  /** App code's indexed receiver Swift holds optional, outside an optional chain: JavaScript's TypeError where it is missing. */
422
422
  elementReceiver(e, target) {
423
- if (this.library || e.questionDotToken || ts.isOptionalChain(e) || this.marks.isUnwrap(target))
423
+ if (this.library || e.questionDotToken || ts.isOptionalChain(e))
424
424
  return target;
425
+ // A compound assignment or update reads the element first.
426
+ const set = ts.isBinaryExpression(e.parent) && e.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && e.parent.left === e;
425
427
  const cell = elementReceiverCell(this.receivers, e);
426
428
  if (cell.cell === 'present')
427
- return this.marks.ownTried(this.receiverCode(cell, keyName(e.argumentExpression)));
429
+ return this.marks.ownTried(this.receiverCode(cell, keyName(e.argumentExpression), set));
430
+ if (this.marks.isUnwrap(target))
431
+ return target;
428
432
  if (!this.typeOf(e.expression).endsWith('?') && (isWriteTarget(e) || !this.widenedParameterRead(ts.skipOuterExpressions(e.expression, ts.OuterExpressionKinds.Parentheses))))
429
433
  return target;
430
434
  const k = e.argumentExpression;
431
435
  const key = swiftString(ts.isStringLiteralLike(k) || ts.isNumericLiteral(k) ? k.text : k.getText());
432
- // A compound assignment or update reads the element first.
433
- const set = ts.isBinaryExpression(e.parent) && e.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && e.parent.left === e;
434
436
  return this.marks.ownTried(this.marks.helper('jsUnwrap', target, set ? `, setting: ${key}` : `, ${key}${onlyNull(this.checker.getTypeAtLocation(e.expression)) ? ', null: true' : ''}`));
435
437
  },
436
438
  /** A receiver that can be missing though its type says not (`x!`, `items[i]`): JavaScript's TypeError when it is. */
@@ -612,10 +614,6 @@ export const accessMethods = {
612
614
  }
613
615
  return this.returnTypeOf(decl);
614
616
  },
615
- /** `assertedUntyped`'s cast: strict code's, to a class or shape whose checked conversion can fail. */
616
- untypedCastChecks(e, t) {
617
- return !this.lenient && this.isObjectRef(e) && this.castChecks(spell(t));
618
- },
619
617
  /** An `assertedUntyped` assertion read as the optional it may be: missing where the value is undefined or null. */
620
618
  /** `x as Iterable<T>` of a value not held as one: whatever x holds iterated, as GetIterator does where it is iterated. */
621
619
  assertedIterable(e) {
@@ -8,27 +8,33 @@ import { isArrayLengthWrite } from "../semantics/throws.js";
8
8
  import { byKey } from "../semantics/spelled.js";
9
9
  import { isKit, isUntyped, spelledType } from "../semantics/types.js";
10
10
  import { untypedUnary } from "../semantics/apis/operators.js";
11
+ import { planUnary } from "../semantics/lower.js";
11
12
  export const assignmentMethods = {
12
13
  prefix(e) {
13
14
  const K = ts.SyntaxKind;
14
15
  const thrown = untypedUnary(this, e);
15
16
  if (thrown)
16
17
  return thrown;
17
- switch (e.operator) {
18
- case K.ExclamationToken: {
19
- const cell = negatedCell(this.conditions, e.operand);
20
- const operand = cell.step === 'bool' ? this.expr(cell.e) : this.cond(e.operand, cell);
21
- return negation(operand);
18
+ const unary = planUnary(e.operator, this.typeOf(e.operand) === 'JSBigInt');
19
+ if (unary) {
20
+ switch (unary.kind) {
21
+ case 'not': {
22
+ const cell = negatedCell(this.conditions, e.operand);
23
+ const operand = cell.step === 'bool' ? this.expr(cell.e) : this.cond(e.operand, cell);
24
+ return negation(operand);
25
+ }
26
+ // `-0` is negative zero; Swift reads the literal `-0` as an integer zero.
27
+ case 'negate':
28
+ if (unary.bigInt)
29
+ return `(-${this.expr(e.operand)})`;
30
+ return ts.isNumericLiteral(e.operand) ? (Number(e.operand.text) === 0 ? '-0.0' : `-${this.expr(e.operand)}`) : `-${this.toNumber(e.operand)}`;
31
+ case 'plus':
32
+ return this.toNumber(e.operand);
33
+ case 'bitNot':
34
+ return unary.bigInt ? `(~${this.expr(e.operand)})` : `${RT.jsBitNot}(${this.toNumber(e.operand)})`;
22
35
  }
23
- // `-0` is negative zero; Swift reads the literal `-0` as an integer zero.
24
- case K.MinusToken:
25
- if (this.typeOf(e.operand) === 'JSBigInt')
26
- return `(-${this.expr(e.operand)})`;
27
- return ts.isNumericLiteral(e.operand) ? (Number(e.operand.text) === 0 ? '-0.0' : `-${this.expr(e.operand)}`) : `-${this.toNumber(e.operand)}`;
28
- case K.PlusToken:
29
- return this.toNumber(e.operand);
30
- case K.TildeToken:
31
- return this.typeOf(e.operand) === 'JSBigInt' ? `(~${this.expr(e.operand)})` : `${RT.jsBitNot}(${this.toNumber(e.operand)})`;
36
+ }
37
+ switch (e.operator) {
32
38
  case K.PlusPlusToken:
33
39
  case K.MinusMinusToken: {
34
40
  const member = this.untypedMember(e.operand);
@@ -54,7 +54,7 @@ export const callsMethods = {
54
54
  return this.marks.ownTried(`${own !== undefined && this.props.has(own) ? `self.${ident(own)}` : this.expr(callee)}.requiredValue()`);
55
55
  if (own !== undefined && (this.props.has(own) || this.signalFields.has(own)))
56
56
  return `self.${ident(own)}.value`;
57
- if (this.framework.signalKind(this.symbolName(callee)) === 'computed' && this.isComputedProperty(callee))
57
+ if (this.framework.signalKind(this.symbolName(callee)) === 'computed' && this.isSwiftComputedProperty(callee))
58
58
  return this.expr(callee);
59
59
  return plain(`${this.expr(callee)}.value`);
60
60
  },
@@ -226,7 +226,7 @@ export const callsMethods = {
226
226
  const builtin = method === 'call' || method === 'apply' ? this.builtinPrototypeCall(method, target, e) : null;
227
227
  if (builtin)
228
228
  return builtin;
229
- if (['call', 'apply', 'bind'].includes(method) && isLibDeclaration(this.checker.getResolvedSignature(e)?.getDeclaration()) && functionParts(this.typeOf(target).replace(/^\((.*)\)[?!]$/, '$1')))
229
+ if (['call', 'apply', 'bind'].includes(method) && isLibDeclaration(this.checker.getResolvedSignature(e)?.getDeclaration()) && (functionParts(this.typeOf(target).replace(/^\((.*)\)[?!]$/, '$1')) || (ts.isPropertyAccessExpression(target) && target.expression.getText() === 'Function.prototype' && ['call', 'apply', 'bind'].includes(target.name.text))))
230
230
  return this.functionMethod(method, target, e);
231
231
  if ((method === 'call' || method === 'apply') && this.programPrototypeMethod(target) && isLibDeclaration(this.checker.getResolvedSignature(e)?.getDeclaration()))
232
232
  return this.functionMethod(method, target, e);
@@ -260,7 +260,7 @@ export const callsMethods = {
260
260
  }
261
261
  // A field holding a function untyped (`private _resolve;`): called with the object as `this`.
262
262
  const field = this.resolve(callee.name)?.valueDeclaration;
263
- if (this.isAny(callee) && field && (ts.isPropertyDeclaration(field) || ts.isPropertySignature(field) || ts.isParameter(field))) {
263
+ if (this.isAny(callee) && field && (ts.isPropertyDeclaration(field) || ts.isPropertySignature(field) || (ts.isMethodSignature(field) && !isLibDeclaration(field)) || ts.isParameter(field))) {
264
264
  const args = e.arguments.some(ts.isSpreadElement) ? `${this.packed(e.arguments, 'JSArray<Any?>', this.restSlot(e, 'Any?'))}.storage` : `[${e.arguments.map((a) => this.restArgument(e, a, 'Any?')).join(', ')}]`;
265
265
  const code = `${RT.jsCallValue}(${this.expr(callee)}, this: ${this.coerce(target, 'Any?')}, optional: ${!!e.questionDotToken}, ${args})`;
266
266
  const t = this.typeOf(e);
@@ -296,6 +296,9 @@ export const callsMethods = {
296
296
  return this.ignoringThisArg(e, target, () => this.call(typedThisArg));
297
297
  if (isKit(spelledType(t), 'JSArray')) {
298
298
  // `observers?.find(…)` on an array TypeScript types as present, which lenient code may hold as undefined: cast to optional, valid either way.
299
+ const checked = !callee.questionDotToken && !ts.isOptionalChain(callee) ? this.receiver(target, method) : null;
300
+ if (checked)
301
+ return this.arrayMethod(method, target, e, '', this.marks.ownTried(checked));
299
302
  const asserted = callee.questionDotToken ? null : assertedReceiverCell(this.receivers, target, method);
300
303
  if (asserted?.cell === 'present')
301
304
  return this.arrayMethod(method, target, e, q, this.marks.ownTried(this.receiverCode(asserted, method)));
@@ -8,7 +8,7 @@ import { isLibDeclaration, withoutDefault, isWriteTarget } from "../semantics/as
8
8
  import { isAsync, isStatic } from "../semantics/throws.js";
9
9
  import { isCoreDeclaration, isShimDeclaration } from "../program/core-facts.js";
10
10
  import { isNativePropertyDecorator } from "../program/patterns.js";
11
- import { prototypeDecorated } from "../semantics/classes.js";
11
+ import { prototypeDecorated, prototypeMethodList } from "../semantics/classes.js";
12
12
  import { isKit, isUntyped, spelledType } from "../semantics/types.js";
13
13
  export const classesMethods = {
14
14
  /** A class's memo field (`computed(fn)`): the memo the instance makes when it is first read, and the field reading its value (a throw rethrown to each reader). */
@@ -346,15 +346,13 @@ export const classesMethods = {
346
346
  return '';
347
347
  const i = this.indent;
348
348
  const name = this.className(cls);
349
- const seen = new Set();
349
+ const plugin = this.pluginFiles.has(cls.getSourceFile().fileName);
350
+ const inherited = plugin ? this.classPlan(cls).inherited : null;
351
+ const kitRoot = plugin ? this.kitRootOf(cls) : null;
350
352
  const entries = [];
351
- for (const m of cls.members) {
352
- if (!ts.isMethodDeclaration(m) || !m.body || isStatic(m) || ts.isPrivateIdentifier(m.name) || ts.isComputedPropertyName(m.name) || m.typeParameters?.length || m.asteriskToken || isAsync(m) || m.parameters.some((p) => p.dotDotDotToken) || this.readsArguments(m))
353
- continue;
354
- const key = m.name.getText().replace(/^['"]|['"]$/g, '');
355
- if (seen.has(key))
356
- continue;
357
- seen.add(key);
353
+ for (const { method: m, key } of prototypeMethodList(cls, {
354
+ skip: (m, key) => isAsync(m) || m.parameters.some((p) => p.dotDotDotToken) || this.readsArguments(m) || (plugin && !inherited.has(key) && !(kitRoot && this.core.kitMember(kitRoot, key)) && !this.facts.isNamed(key)),
355
+ })) {
358
356
  const sig = this.emittedSignature(m);
359
357
  const args = sig.params.map((p, k) => this.throwingConverts(() => this.presentFromAny(`${RT.jsArg}(__a, ${k})`, p.type, true, true)));
360
358
  const call = this.marks.tryIf(this.throwsInfo.fn(m), `__o.${ident(key)}(${args.join(', ')})`);
@@ -2,7 +2,7 @@
2
2
  import ts from 'typescript';
3
3
  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
- import { equalOption } from "../semantics/signals.js";
5
+ import { equalOption, isReadonlySignalProperty } from "../semantics/signals.js";
6
6
  import { isTemplateMethod } from "../semantics/trust.js";
7
7
  import { extendsHeritage, hasModifier, nonSuperStatements } from "../semantics/ast.js";
8
8
  import { nullableTypeNode, resultsAreUndefinedElements } from "../semantics/lang.js";
@@ -356,7 +356,7 @@ export const componentMethods = {
356
356
  return this.throwsInfo.fn(held.arguments[0]) ? ` var ${name}: ${t} {\n get throws { try ${read} }\n }` : ` var ${name}: ${t} { ${read} }`;
357
357
  },
358
358
  /** Whether a `Signal<T>` node is lowered as a Swift computed property (`var x: T`) rather than a `Signal<T>` instance. */
359
- isComputedProperty(n) {
359
+ isSwiftComputedProperty(n) {
360
360
  if (ts.isIdentifier(n) && this.moduleComputed(n))
361
361
  return true;
362
362
  const decl = ts.isIdentifier(n) || ts.isPropertyAccessExpression(n) ? this.resolve(n)?.valueDeclaration : n;
@@ -368,7 +368,7 @@ export const componentMethods = {
368
368
  }
369
369
  if (ts.isPropertyDeclaration(decl) && ts.isClassDeclaration(decl.parent) && !this.pluginFiles.has(decl.getSourceFile().fileName) && decl.initializer) {
370
370
  const callee = this.calleeName(decl.initializer);
371
- if (this.framework.memoized(decl, this.checker) || /\.asReadonly$/.test(callee) || (ts.isIdentifier(decl.initializer) && !!this.moduleComputed(decl.initializer)))
371
+ if (isReadonlySignalProperty(decl, this.checker, this.framework, callee) || (ts.isIdentifier(decl.initializer) && !!this.moduleComputed(decl.initializer)))
372
372
  return true;
373
373
  }
374
374
  return false;
@@ -160,7 +160,7 @@ export const controlFlowMethods = {
160
160
  let code;
161
161
  const block = s.catchClause ? this.block(s.tryBlock) : '';
162
162
  // A catch whose try block cannot throw never runs: the block alone.
163
- if (s.catchClause && !this.throwsInfo.statements([s.tryBlock])) {
163
+ if (s.catchClause && !this.throwsInfo.statements([s.tryBlock]) && !/\btry\s/.test(block)) {
164
164
  this.catchless.add(s.tryBlock);
165
165
  code = this.scope(s.tryBlock);
166
166
  }
@@ -146,8 +146,11 @@ export const conversionMethods = {
146
146
  return null;
147
147
  // Given to the language's or a platform's API (`list.map(f)`, which rethrows what `f` may throw), which never compares it: as it is.
148
148
  if ((ts.isCallExpression(p) || ts.isNewExpression(p)) && p.arguments?.includes(e)) {
149
- const callee = this.checker.getResolvedSignature(p)?.getDeclaration();
150
- if (callee && callee.getSourceFile().isDeclarationFile && !isCoreDeclaration(callee))
149
+ const sig = this.checker.getResolvedSignature(p);
150
+ const callee = sig?.getDeclaration();
151
+ const paramDecl = sig?.getParameters()[p.arguments.indexOf(e)]?.valueDeclaration;
152
+ const paramType = paramDecl ? this.checker.getTypeAtLocation(paramDecl) : undefined;
153
+ if (callee && callee.getSourceFile().isDeclarationFile && !isCoreDeclaration(callee) && paramType && this.checker.getNonNullableType(paramType).getCallSignatures().length > 0)
151
154
  return null;
152
155
  }
153
156
  return decl;
@@ -513,7 +513,7 @@ export class CoreAPI extends KitTypes {
513
513
  return m?.kind === 'var' && !!m.throws;
514
514
  }
515
515
  /** A kit property's value or method's result the kit holds optional, read where core's typings say present. */
516
- kitNil(x) {
516
+ swiftKitNil(x) {
517
517
  try {
518
518
  x = ts.skipOuterExpressions(x, ts.OuterExpressionKinds.Parentheses);
519
519
  if (ts.isCallExpression(x) && ts.isIdentifier(x.expression)) {
@@ -548,7 +548,7 @@ export class CoreAPI extends KitTypes {
548
548
  optionalKitValue(x) {
549
549
  while (ts.isParenthesizedExpression(x))
550
550
  x = x.expression;
551
- if (!this.t.lenient && !this.t.library && this.kitNil(x))
551
+ if (!this.t.lenient && !this.t.library && this.swiftKitNil(x))
552
552
  return true;
553
553
  if (ts.isIdentifier(x)) {
554
554
  const sym = this.t.resolve(x);
@@ -258,7 +258,7 @@ export const declarationsMethods = {
258
258
  if (!js) {
259
259
  const value = this.coerce(init, this.typeOf(init));
260
260
  // What the kit holds optional though the declarations say present (`getActualSize()`): JavaScript's TypeError destructuring undefined.
261
- if (ts.isObjectBindingPattern(name) && this.marks.isUnwrap(value) && !this.lenient && this.core.kitNil(init))
261
+ if (ts.isObjectBindingPattern(name) && this.marks.isUnwrap(value) && !this.lenient && this.core.swiftKitNil(init))
262
262
  return `: ${this.typeOf(init)} = try ${this.required(init, this.marks.unwrapInner(value))}`;
263
263
  return `: ${this.typeOf(init)} = ${this.marks.tryBefore(this.tryPrefix(init), value)}`;
264
264
  }
@@ -43,7 +43,7 @@ export const expressionsMethods = {
43
43
  cond(e, cell) {
44
44
  const sub = substitutedExpr(this.subst, e);
45
45
  if (sub)
46
- return this.typeOf(sub.bare) === 'Bool' ? sub.code : `${RT.jsTruthy}(${sub.code})`;
46
+ return this.typeOf(sub.bare) === 'Bool' ? sub.code : `${RT.jsTruthy}(${this.marks.isUnwrap(sub.code) ? this.marks.unwrapInner(sub.code) : sub.code})`;
47
47
  if (cell === undefined)
48
48
  cell = conditionCell(this.conditions, e);
49
49
  const code = this.truthy(cell);
@@ -148,10 +148,11 @@ export const expressionsMethods = {
148
148
  const t = this.lenientRef(declared) !== declared ? optionalType(declared) : declared;
149
149
  const exprType = this.typeOf(a);
150
150
  const rt = isUntyped(spelledType(t)) && !isUntyped(spelledType(exprType)) && exprType !== 'Void' ? exprType : t;
151
+ const retType = this.lenientRef(rt) !== rt ? optionalType(rt) : rt;
151
152
  const tp = this.tryPrefix(a);
152
153
  const retVal = rt !== t ? this.fromAnyCode(this.expr(a.left), rt, true) : this.expr(a.left);
153
154
  const retThrows = tp || /\btry\b/.test(retVal);
154
- return `({ () ${retThrows ? 'throws ' : ''}-> ${rt} in ${tp}${this.binary(a)}; return ${retVal} }())`;
155
+ return `({ () ${retThrows ? 'throws ' : ''}-> ${retType} in ${tp}${this.binary(a)}; return ${retVal} }())`;
155
156
  }
156
157
  if (ts.isParenthesizedExpression(e)) {
157
158
  const inner = this.expr(e.expression);
@@ -271,6 +272,9 @@ export const expressionsMethods = {
271
272
  const raw = this.untypedMemberValue(e.expression);
272
273
  if (raw)
273
274
  return raw;
275
+ const maybe = this.maybeUndefined(e.expression);
276
+ if (maybe)
277
+ return this.marks.leading(`(${maybe} as Any?)`, maybe);
274
278
  }
275
279
  // `<Array<View>>views` of a ViewBase[]: Swift's arrays of the two are distinct types, so the elements are read as the asserted one, in a copy unless the array already is one.
276
280
  const fromArray = /^JSArray<(.+)>[?!]?$/.exec(from), toArray = /^JSArray<(.+)>[?!]?$/.exec(to);
@@ -263,7 +263,7 @@ export const fromAnyMethods = {
263
263
  // An interface classes implement: an object conforming to it as it is, any other read by its keys.
264
264
  return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}, { (${RT.jsFlat}($0) as? ${base}) ?? ${base}Object(jsObject: $0) })` : `{ (__o: Any?) -> ${base} in (${RT.jsFlat}(__o) as? ${base}) ?? ${base}Object(jsObject: __o) }(${code})`;
265
265
  }
266
- if (this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), base) || !!this.shapes.named(base) || (!this.library && this.core.viewable(base))) {
266
+ if ((!this.classNamed(base) && (this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), base) || !!this.shapes.named(base))) || (!this.library && this.core.viewable(base))) {
267
267
  this.used.add(base);
268
268
  // An object of the interface's class already is the object read (a receiver `call` passes); any other is read by its keys.
269
269
  return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}, { (${RT.jsFlat}($0) as? ${base}) ?? ${this.viewOf(base, '$0')} })` : `{ (__o: Any?) -> ${base} in (${RT.jsFlat}(__o) as? ${base}) ?? ${this.viewOf(base, '__o')} }(${code})`;
@@ -8,7 +8,7 @@ import { returnCell } from "../semantics/placement.js";
8
8
  import { hasModifier, isLibDeclaration, withoutDefault, implementationOf, declaresThis } from "../semantics/ast.js";
9
9
  import { isAsync, isStatic } from "../semantics/throws.js";
10
10
  import { isCoreDeclaration } from "../program/core-facts.js";
11
- import { methodValues } from "../semantics/lang.js";
11
+ import { builtinConstructorSlot, methodValues } from "../semantics/lang.js";
12
12
  import { baseMethod } from "../semantics/classes.js";
13
13
  import { isUntyped, spelledType } from "../semantics/types.js";
14
14
  export const functionsMethods = {
@@ -261,11 +261,9 @@ export const functionsMethods = {
261
261
  const conversion = { Number: [RT.jsToNumber, 'Double'], String: [RT.jsToString, 'String'], Boolean: [RT.jsTruthy, 'Bool'] }[e.text];
262
262
  if (!conversion)
263
263
  return null;
264
- const context = this.checker.getContextualType(e);
265
- const slot = context && this.checker.getNonNullableType(context).getCallSignatures()[0];
266
- // Placed untyped (`const f: any = Number`, `s.constructor === String`): singleton builtin constructor.
267
- if (!slot)
268
- return `js${e.text}Constructor`;
264
+ const { singleton, slot } = builtinConstructorSlot(e, this.checker, (c) => isUntyped(spelledType(this.type(c, e))));
265
+ if (singleton)
266
+ return singleton;
269
267
  const param = slot?.getParameters()[0];
270
268
  const t = param ? this.type(this.checker.getTypeOfSymbolAtLocation(param, e), e) : 'Any?';
271
269
  const call = p && ts.isCallExpression(p) && p.arguments[0] === e && ts.isPropertyAccessExpression(p.expression) ? p.expression.expression : null;
@@ -390,6 +388,7 @@ export const functionsMethods = {
390
388
  const throws = !isAsync(fn) && this.throwsInfo.fn(fn) ? 'throws ' : '';
391
389
  // A function expression's name is only for itself: one that never refers to itself is an anonymous function.
392
390
  if (fn.name && refersTo(fn.body, this.checker.getSymbolAtLocation(fn.name), this.checker)) {
391
+ this.refuseNamedGenerator(fn);
393
392
  const fnName = ident(fn.name.text);
394
393
  const extra = this.unusedParameters(fn).map((t, k) => `_ __unused${k}: ${t}`);
395
394
  const fnParams = [this.params(fn, false), ...extra, ...pad.map((p) => (p.startsWith('_ ') ? p : `_ ${p}`))].filter(Boolean).join(', ');
@@ -161,7 +161,7 @@ export const globalCallsMethods = {
161
161
  const declared = this.checker.getResolvedSignature(e)?.getDeclaration();
162
162
  const isFunctionValue = !declared || ts.isJSDocSignature(declared) || !('body' in declared && declared.body) || ts.isArrowFunction(declared) || ts.isFunctionExpression(declared);
163
163
  // A function held untyped (one of several function types): called as script calls it.
164
- if (this.isAny(callee)) {
164
+ if (this.isAny(callee) && !(declared && ts.isFunctionDeclaration(declared) && declared.body)) {
165
165
  const code = `${RT.jsCall}(${this.expr(callee)}${this.untypedArgs(e)})`;
166
166
  const t = this.typeOf(e);
167
167
  return isUntyped(spelledType(t)) || t === 'Void' ? code : this.fromAnyCode(code, t, true);