@nstudio/nativescript-compiler 9.2.0-alpha.16 → 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 (186) hide show
  1. package/README.md +3 -0
  2. package/dist/kit/kit-index.js +9 -0
  3. package/dist/kotlin/access.js +14 -15
  4. package/dist/kotlin/arguments.js +2 -2
  5. package/dist/kotlin/assignment.js +22 -13
  6. package/dist/kotlin/builtins.js +67 -0
  7. package/dist/kotlin/calls.js +3 -2
  8. package/dist/kotlin/class-declaration.js +16 -1
  9. package/dist/kotlin/class-methods.js +2 -2
  10. package/dist/kotlin/components.js +2 -7
  11. package/dist/kotlin/core-api.js +3 -22
  12. package/dist/kotlin/declarations.js +86 -9
  13. package/dist/kotlin/expression-statements.js +13 -1
  14. package/dist/kotlin/functions.js +2 -4
  15. package/dist/kotlin/global-calls.js +1 -4
  16. package/dist/kotlin/literals.js +3 -10
  17. package/dist/kotlin/names.js +6 -4
  18. package/dist/kotlin/native/api.js +1 -1
  19. package/dist/kotlin/native/classfiles.js +2 -13
  20. package/dist/kotlin/operators.js +36 -30
  21. package/dist/kotlin/optional-chains.js +3 -10
  22. package/dist/kotlin/overrides.js +5 -17
  23. package/dist/kotlin/placement.js +1 -12
  24. package/dist/kotlin/state-backend.js +6 -2
  25. package/dist/kotlin/statements.js +1 -13
  26. package/dist/kotlin/translator.js +3 -11
  27. package/dist/kotlin/type-tests.js +1 -1
  28. package/dist/kotlin/types.js +6 -23
  29. package/dist/program/core-facts.js +9 -0
  30. package/dist/semantics/classes.js +15 -0
  31. package/dist/semantics/facts.js +38 -2
  32. package/dist/semantics/lang.js +29 -0
  33. package/dist/semantics/lower.js +144 -0
  34. package/dist/semantics/lowering-methods.js +120 -3
  35. package/dist/semantics/marks.js +30 -0
  36. package/dist/semantics/placement.js +9 -3
  37. package/dist/semantics/refusals.js +12 -11
  38. package/dist/semantics/signals.js +11 -0
  39. package/dist/semantics/states/missing.js +7 -0
  40. package/dist/semantics/tdz.js +142 -8
  41. package/dist/semantics/throws.js +1 -1
  42. package/dist/semantics/translator-methods.js +1 -1
  43. package/dist/swift/access.js +13 -17
  44. package/dist/swift/assignment.js +30 -16
  45. package/dist/swift/calls.js +13 -5
  46. package/dist/swift/classes.js +22 -10
  47. package/dist/swift/components.js +3 -7
  48. package/dist/swift/control-flow.js +1 -1
  49. package/dist/swift/conversion.js +5 -2
  50. package/dist/swift/core-api.js +11 -31
  51. package/dist/swift/declarations.js +1 -6
  52. package/dist/swift/expression-statements.js +7 -0
  53. package/dist/swift/expressions.js +6 -2
  54. package/dist/swift/from-any.js +1 -1
  55. package/dist/swift/functions.js +5 -6
  56. package/dist/swift/global-calls.js +1 -5
  57. package/dist/swift/lenient.js +0 -7
  58. package/dist/swift/literals.js +8 -3
  59. package/dist/swift/method-values.js +1 -19
  60. package/dist/swift/modules.js +5 -3
  61. package/dist/swift/names.js +3 -12
  62. package/dist/swift/native/api.js +3 -1
  63. package/dist/swift/native/calls.js +1 -1
  64. package/dist/swift/native/dispatch.js +2 -8
  65. package/dist/swift/object-classes.js +84 -1
  66. package/dist/swift/operators.js +37 -34
  67. package/dist/swift/optional-chains.js +1 -8
  68. package/dist/swift/parameters.js +0 -4
  69. package/dist/swift/placement.js +5 -15
  70. package/dist/swift/results.js +0 -4
  71. package/dist/swift/state-backend.js +3 -2
  72. package/dist/swift/statements.js +1 -13
  73. package/dist/swift/static-calls.js +2 -3
  74. package/dist/swift/syntax.js +9 -5
  75. package/dist/swift/translator.js +1 -11
  76. package/dist/swift/type-facts.js +3 -3
  77. package/dist/swift/types.js +3 -3
  78. package/dist/targets/ios/build.js +1 -1
  79. package/dist/types/adapter-api.d.ts +3 -3
  80. package/kit-android/generated/kotlin/org/nativescript/kit/__Modules.kt +1 -0
  81. package/kit-android/generated/kotlin/org/nativescript/kit/__Objects.kt +525 -99
  82. package/kit-android/generated/kotlin/org/nativescript/kit/accessibility_accessibility_common.kt +2 -2
  83. package/kit-android/generated/kotlin/org/nativescript/kit/application_application_common.kt +29 -6
  84. package/kit-android/generated/kotlin/org/nativescript/kit/application_helpers_common.kt +14 -0
  85. package/kit-android/generated/kotlin/org/nativescript/kit/color_color_utils.kt +3 -3
  86. package/kit-android/generated/kotlin/org/nativescript/kit/css_mediaquery_index.kt +49 -1
  87. package/kit-android/generated/kotlin/org/nativescript/kit/data_observable_array_index.kt +0 -8
  88. package/kit-android/generated/kotlin/org/nativescript/kit/data_observable_index.kt +0 -16
  89. package/kit-android/generated/kotlin/org/nativescript/kit/data_virtual_array_index.kt +6 -4
  90. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_index.kt +19 -7
  91. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_http_request_internal_common.kt +14 -0
  92. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_index.kt +19 -10
  93. package/kit-android/generated/kotlin/org/nativescript/kit/matrix_index.kt +17 -29
  94. package/kit-android/generated/kotlin/org/nativescript/kit/media_query_list_index.kt +144 -22
  95. package/kit-android/generated/kotlin/org/nativescript/kit/npm_css_what_src_parse.kt +8 -3
  96. package/kit-android/generated/kotlin/org/nativescript/kit/org.nativescript.NativeScriptLifecycleCallbacks.kt +2 -10
  97. package/kit-android/generated/kotlin/org/nativescript/kit/ui_builder_index.kt +0 -2
  98. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_bindable_expression_parser.kt +6 -10
  99. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +531 -8
  100. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_base_index.kt +0 -9
  101. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_weak_event_listener_index.kt +3 -3
  102. package/kit-android/generated/kotlin/org/nativescript/kit/ui_styling_style_index.kt +19 -0
  103. package/kit-android/generated/kotlin/org/nativescript/kit/ui_styling_style_properties.kt +5 -2
  104. package/kit-android/generated/kotlin/org/nativescript/kit/ui_styling_style_scope.kt +232 -174
  105. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_view_text_view_common.kt +1 -1
  106. package/kit-android/generated/kotlin/org/nativescript/kit/utils_android_runtime_version.kt +75 -0
  107. package/kit-android/generated/manifest.json +21 -18
  108. package/kit-android/generated/source-lines.json +1 -1
  109. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Array.kt +547 -51
  110. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Intl.kt +1 -1
  111. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/JSON.kt +52 -6
  112. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Language.kt +33 -0
  113. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +9 -1
  114. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Strings.kt +32 -18
  115. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Values.kt +137 -28
  116. package/kit-apple/Overlays/xml-free/Core/ui.builder.index.swift +1 -1
  117. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +14 -10
  118. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +3 -9
  119. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +20 -21
  120. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_index_section_view_ios_android.swift +5 -7
  121. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_ios_android_.swift +130 -0
  122. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_oldIndex_newIndex.swift +2 -4
  123. package/kit-apple/Sources/NativeScriptKit/Core/Object_specified_substituted_reads.swift +115 -0
  124. package/kit-apple/Sources/NativeScriptKit/Core/Object_substituted_values_reads.swift +113 -0
  125. package/kit-apple/Sources/NativeScriptKit/Core/Object_substituted_values_reads_.swift +113 -0
  126. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +348 -330
  127. package/kit-apple/Sources/NativeScriptKit/Core/application.application.ios.swift +358 -359
  128. package/kit-apple/Sources/NativeScriptKit/Core/application.helpers-common.swift +47 -29
  129. package/kit-apple/Sources/NativeScriptKit/Core/connectivity.index.ios.swift +3 -1
  130. package/kit-apple/Sources/NativeScriptKit/Core/css-mediaquery.index.swift +95 -53
  131. package/kit-apple/Sources/NativeScriptKit/Core/css.CSS3Parser.swift +1 -1
  132. package/kit-apple/Sources/NativeScriptKit/Core/css.parser.swift +1 -1
  133. package/kit-apple/Sources/NativeScriptKit/Core/data.observable-array.index.swift +2 -2
  134. package/kit-apple/Sources/NativeScriptKit/Core/file-system.file-system-access.ios.swift +52 -43
  135. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.http-request-internal-common.swift +18 -0
  136. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.index.ios.swift +66 -51
  137. package/kit-apple/Sources/NativeScriptKit/Core/image-source.index.ios.swift +67 -51
  138. package/kit-apple/Sources/NativeScriptKit/Core/js-libs.easysax.easysax.swift +24 -6
  139. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +143 -32
  140. package/kit-apple/Sources/NativeScriptKit/Core/manifest.json +30 -19
  141. package/kit-apple/Sources/NativeScriptKit/Core/media-query-list.index.swift +190 -78
  142. package/kit-apple/Sources/NativeScriptKit/Core/native-window.native-window.ios.swift +1 -1
  143. package/kit-apple/Sources/NativeScriptKit/Core/npm.css-what.src.parse.swift +205 -201
  144. package/kit-apple/Sources/NativeScriptKit/Core/npm.css-what.src.stringify.swift +41 -42
  145. package/kit-apple/Sources/NativeScriptKit/Core/npm.css-what.src.types.swift +1 -1
  146. package/kit-apple/Sources/NativeScriptKit/Core/trace.index.swift +2 -2
  147. package/kit-apple/Sources/NativeScriptKit/Core/ui.animation.index.ios.swift +77 -65
  148. package/kit-apple/Sources/NativeScriptKit/Core/ui.builder.index.swift +4 -4
  149. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.properties.index.swift +1272 -824
  150. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +2 -2
  151. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.index.ios.swift +8 -8
  152. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-common.swift +1 -1
  153. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.frame-common.swift +2 -1
  154. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.index.ios.swift +6 -6
  155. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.flexbox-layout.index.ios.swift +22 -21
  156. package/kit-apple/Sources/NativeScriptKit/Core/ui.page.index.ios.swift +202 -188
  157. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +2 -6
  158. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.index.ios.swift +3 -3
  159. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.background.ios.swift +2 -2
  160. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.clip-path-function.swift +1 -1
  161. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-animation-parser.swift +1 -1
  162. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +2 -2
  163. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.font-common.swift +2 -2
  164. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.style-scope.swift +869 -838
  165. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.style.index.swift +46 -31
  166. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.formatted-string.swift +1 -2
  167. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-view.text-view-common.swift +1 -1
  168. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.index.ios.swift +2 -2
  169. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.modal-transition.ios.swift +4 -4
  170. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.page-transition.ios.swift +2 -2
  171. package/kit-apple/Sources/NativeScriptKit/Core/ui.transition.shared-transition-helper.ios.swift +17 -17
  172. package/kit-apple/Sources/NativeScriptKit/Core/utils.android-runtime-version.swift +77 -0
  173. package/kit-apple/Sources/NativeScriptKit/Core/utils.debug-source.swift +2 -2
  174. package/kit-apple/Sources/NativeScriptKit/Core/xhr.index.swift +62 -61
  175. package/kit-apple/Sources/NativeScriptKit/Runtime/Array.swift +4 -0
  176. package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +2 -0
  177. package/kit-apple/Sources/NativeScriptKit/Runtime/Interop.swift +1 -1
  178. package/kit-apple/Sources/NativeScriptKit/Runtime/Intl.swift +1 -1
  179. package/kit-apple/Sources/NativeScriptKit/Runtime/Iterators.swift +1 -1
  180. package/kit-apple/Sources/NativeScriptKit/Runtime/JSON.swift +413 -73
  181. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +3 -2
  182. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +14 -1
  183. package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +1 -0
  184. package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +1 -0
  185. package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +2 -0
  186. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  // Literals as Swift: arrays, objects and dynamic objects.
2
2
  import ts from 'typescript';
3
- import { functionParts, ident, identPath, initOrder, isNullish, isOptional, label, optionalType, splitTopLevel, swiftString, withoutThenables, spell, RT } from "./syntax.js";
3
+ import { functionParts, ident, identPath, implicitType, initOrder, isNullish, isOptional, label, optionalType, splitTopLevel, swiftString, withoutThenables, spell, RT } from "./syntax.js";
4
4
  import { assertedOperand, evolvingElementContext, intersectionAliasMembers, isTypeParameterType, literalKey, openSpreadType, spreadOperand, unquoted } from "../semantics/lang.js";
5
5
  import { place } from "../semantics/placement.js";
6
6
  import { holdsNil, literalNotes, signatureField, shapePlanOfLiteral, spelledOptional, spreadElementNeedsMap, resultShapeNamed } from "../semantics/shapes.js";
@@ -300,7 +300,7 @@ export const literalsMethods = {
300
300
  }
301
301
  };
302
302
  // A field the class holds implicitly unwrapped (`shapeHeld`) takes what the literal gives as optional, undefined included.
303
- const loose = (want) => !!want && target === name && this.shapeHeld({ type: want }) === `${want}!`;
303
+ const loose = (want) => !!want && target === name && this.shapeHeld({ type: want }) === implicitType(want);
304
304
  // Methods that read `this` see the object through a weak reference the literal sets once it exists.
305
305
  // A function expression as a member (`onViewLoaded: function () { this.loadedCount++ }`) reads the object as `this` too.
306
306
  const thisFunction = (p) => ts.isPropertyAssignment(p) && ts.isFunctionExpression(p.initializer) && thisNodes(p.initializer).length > 0;
@@ -390,7 +390,12 @@ export const literalsMethods = {
390
390
  }
391
391
  else if (ts.isMethodDeclaration(p)) {
392
392
  const key = literalKey(p.name, this.checker) ?? this.symbolMemberName(p.name) ?? p.name.getText();
393
- const want = functionParts((order.find((f) => f.name === key)?.type ?? '').replace(/^\((.*)\)[?!]$/, '$1'));
393
+ const fieldType = order.find((f) => f.name === key)?.type ?? '';
394
+ if (isUntyped(spelledType(fieldType))) {
395
+ given.set(key, this.untypedMethod(p));
396
+ continue;
397
+ }
398
+ const want = functionParts(fieldType.replace(/^\((.*)\)[?!]$/, '$1'));
394
399
  // An unannotated method returning an object literal makes it against its field's declared result, as TypeScript types the returned literal.
395
400
  const sig = !p.type && want && want.result !== 'Void' ? this.checker.getSignatureFromDeclaration(p) : undefined;
396
401
  const literalResult = !!sig && !!this.checker.getReturnTypeOfSignature(sig).symbol?.declarations?.some(ts.isObjectLiteralExpression);
@@ -2,7 +2,7 @@
2
2
  import ts from 'typescript';
3
3
  import { ident, isMethodValue, optionalType, scriptLength, swiftString, RT } from "./syntax.js";
4
4
  import { forwardedSetter, inferredFunctionName, methodValues } from "../semantics/lang.js";
5
- import { thisNodes, declaresThis } from "../semantics/ast.js";
5
+ import { declaresThis } from "../semantics/ast.js";
6
6
  import { isUntyped, spelledType } from "../semantics/types.js";
7
7
  import { isStatic } from "../semantics/throws.js";
8
8
  export const methodValuesMethods = {
@@ -158,22 +158,4 @@ export const methodValuesMethods = {
158
158
  const fnName = !this.library ? inferredFunctionName(fn) : '';
159
159
  return fnName ? `${RT.jsMethodFunction}(${swiftString(fnName)}, ${scriptLength(fn)}, ${method})` : `(${method} as JSMethod)`;
160
160
  },
161
- /** Runs `body` with `this` in `fn` (and in the arrow functions inside it) read as `name`. */
162
- withThis(fn, name, untyped, body) {
163
- const nodes = thisNodes(fn);
164
- for (const n of nodes) {
165
- this.subst.set(n, name);
166
- if (untyped)
167
- this.untypedThis.add(n);
168
- }
169
- try {
170
- return body();
171
- }
172
- finally {
173
- for (const n of nodes) {
174
- this.subst.delete(n);
175
- this.untypedThis.delete(n);
176
- }
177
- }
178
- },
179
161
  };
@@ -1,7 +1,7 @@
1
1
  // Module-level declarations as Swift: modules, variables, namespaces, constants, interfaces and protocols.
2
2
  import { setLossSite } from "../semantics/losses.js";
3
3
  import ts from 'typescript';
4
- import { NONISOLATED_DEINIT, SWIFT_GLOBAL_FUNCTIONS, escapingFunction, functionParts, ident, identPath, indented, isFunctionType, isNullish, isOptional, nativeResult, nativeZero, optionalType, swiftString, RT } from "./syntax.js";
4
+ import { NONISOLATED_DEINIT, SWIFT_GLOBAL_FUNCTIONS, escapingFunction, functionParts, ident, identPath, implicitType, indented, isFunctionType, isNullish, isOptional, nativeResult, nativeZero, optionalType, swiftString, RT } from "./syntax.js";
5
5
  import { lookupClass, lookupMember } from "./native/sdk.js";
6
6
  import { boundNames, hasModifier, isLibDeclaration, moduleBlockVars, redeclaredVar } from "../semantics/ast.js";
7
7
  import { enteredGuard, onMainThread } from "./native/bridging.js";
@@ -150,6 +150,8 @@ export const modulesMethods = {
150
150
  }
151
151
  if ((library || this.appMembersByName) && st.members.some((m) => ts.isAccessor(m) && !isStatic(m)))
152
152
  later(() => this.prototypeAccessors(st));
153
+ if (!library && this.facts.prototypeClasses().has(st))
154
+ later(() => this.prototypeMethods(st));
153
155
  for (const line of inits)
154
156
  later(() => line);
155
157
  // Library mode: its statics and decorators run once it is defined.
@@ -682,7 +684,7 @@ export const modulesMethods = {
682
684
  });
683
685
  const signature = (m) => `func ${m.name}(${m.params.map((p) => `_ ${p.name}: ${isFunctionType(p.type) ? `@escaping ${p.type}` : p.type}`).join(', ')}) throws${m.ret === 'Void' ? '' : ` -> ${m.ret}`}`;
684
686
  const fnType = (m) => `(${m.params.map((p) => p.type).join(', ')}) throws -> ${m.ret.replace(/!$/, '?')}`;
685
- const lines = [`protocol ${name}: JSDynamic {`];
687
+ const lines = [`@MainActor protocol ${name}: JSDynamic {`];
686
688
  const params = (m) => m.params.map((p) => `_ ${p.name}: ${isFunctionType(p.type) ? `@escaping ${p.type}` : p.type}`).join(', ');
687
689
  const requirements = (owner) => {
688
690
  for (const f of fields)
@@ -936,7 +938,7 @@ ${members.join('\n')}
936
938
  return isFunctionType(f.type) ? `(${f.type})?` : this.nullableRef(f.type);
937
939
  // An app's object field holds undefined too, as a literal asserted to the type may give it (`{ …, view } as
938
940
  // ItemEventData` before the view exists); a read that uses it unwraps it there.
939
- return !this.library && !isOptional(f.type) && !f.type.endsWith('!') && !isFunctionType(f.type) && this.nullableRef(f.type) !== f.type ? `${f.type}!` : f.type;
941
+ return !this.library && !isOptional(f.type) && !f.type.endsWith('!') && !isFunctionType(f.type) && this.nullableRef(f.type) !== f.type ? implicitType(f.type) : f.type;
940
942
  },
941
943
  membersWritten() {
942
944
  return this.facts.assignedMembers();
@@ -159,11 +159,6 @@ export const namesMethods = {
159
159
  const d = sym?.valueDeclaration;
160
160
  return !!d && ts.isModuleDeclaration(d) && !d.getSourceFile().isDeclarationFile;
161
161
  },
162
- /** The kit class a mixin class (`applyMixins(View, [Extended])`) is applied to. */
163
- mixinOf(sym) {
164
- const d = sym?.valueDeclaration;
165
- return d && ts.isClassDeclaration(d) ? this.patterns.mixinTarget(d) : null;
166
- },
167
162
  /**
168
163
  * The name a translated declaration has: an import renamed (`install as
169
164
  * installGestureHandler`) names its export, and a module-level name that
@@ -183,10 +178,6 @@ export const namesMethods = {
183
178
  return e.text;
184
179
  return target.name;
185
180
  },
186
- /** A module-level function or variable's Swift name. */
187
- topName(decl, name) {
188
- return this.topNames().get(decl) ?? name;
189
- },
190
181
  /** `name` in `file`'s module: the shortest end of its path no other name has taken (`label__index`, else `label__two_index`). */
191
182
  uniqueTopName(name, file) {
192
183
  return moduleSuffixedName(name, file, this.topTaken);
@@ -195,7 +186,7 @@ export const namesMethods = {
195
186
  * App mode: a type name Swift code already has unqualified (the standard library's, the runtime's, the app module's own
196
187
  * Swift, or a native module's the app imports), which a program type of that name would hide from the app.
197
188
  */
198
- nativeClash(name) {
189
+ swiftTypeClash(name) {
199
190
  return !this.library && (SWIFT_NATIVE_TYPES.has(name) || runtimeTypeName(name) || this.appSwiftNames.has(name) || this.importedTypeNames().has(name));
200
191
  },
201
192
  /** The Swift type names of `nativeModules` and of the SDK modules whose declarations the program's code names. */
@@ -285,7 +276,7 @@ export const namesMethods = {
285
276
  this.kitClashes.push(name);
286
277
  // A type the hand-written kit declares for itself (Signals' `Source`), or an app's type named as one Swift has already
287
278
  // (`Result`): the generated one takes its module's name.
288
- const internalClash = !!this.library?.internalTypes?.has(name) || (list.some((x) => typeLike(x.decl) || ts.isInterfaceDeclaration(x.decl)) && this.nativeClash(name));
279
+ const internalClash = !!this.library?.internalTypes?.has(name) || (list.some((x) => typeLike(x.decl) || ts.isInterfaceDeclaration(x.decl)) && this.swiftTypeClash(name));
289
280
  if (list.length < 2 && !kitClash && !internalClash)
290
281
  continue;
291
282
  // The app's first declaration keeps its name; the others take their module's.
@@ -335,7 +326,7 @@ export const namesMethods = {
335
326
  if (ts.isModuleDeclaration(st))
336
327
  collect(st);
337
328
  for (const [name, list] of hoisted) {
338
- if (!byName.has(name) && list.length < 2 && !this.core.has(name) && !this.nativeClash(name))
329
+ if (!byName.has(name) && list.length < 2 && !this.core.has(name) && !this.swiftTypeClash(name))
339
330
  continue;
340
331
  for (const x of list)
341
332
  this.renamedTop.set(x.decl, `${name}__${(this.namespacePath(x.ns) ?? '').replace(/\./g, '_')}`);
@@ -29,7 +29,9 @@ export class NativeAPI {
29
29
  if (known)
30
30
  return /[\\/]objc![^\\/]*\.d\.ts$/.test(decl.getSourceFile().fileName) || tableDeclares(known, decl) ? known : null;
31
31
  // An app's own declaration of an SDK type newer than the published typings (`declare class UIArrangementViewController`
32
- // in a .d.ts of its own): the SDK module whose table has a type of that name.
32
+ // in a .d.ts of its own): the SDK module whose table has a type of that name (only when the Apple SDK is present).
33
+ if (process.platform !== 'darwin')
34
+ return null;
33
35
  const file = decl.getSourceFile();
34
36
  if (!file.isDeclarationFile || /[\\/]node_modules[\\/]/.test(file.fileName))
35
37
  return null;
@@ -435,7 +435,7 @@ export const nativeCallsMethods = {
435
435
  * Whether a typings declaration's Swift binding holds nil (an optional): a property's value, a method's result, a
436
436
  * parameter's argument, or a parameter of a block the method takes. False where the tables have no such member.
437
437
  */
438
- holdsNil(d) {
438
+ iosHoldsNil(d) {
439
439
  try {
440
440
  const block = ts.isParameter(d) && ts.isFunctionTypeNode(d.parent) && ts.isParameter(d.parent.parent) ? d.parent.parent : null;
441
441
  const param = block ?? (ts.isParameter(d) ? d : null);
@@ -3,6 +3,7 @@ import { CF_CLASSES, functionParts, RT } from "../syntax.js";
3
3
  import { posted } from "./bridging.js";
4
4
  import { lookupClass, lookupInit, nativeTable } from "./sdk.js";
5
5
  import { compareText } from "../../program/order.js";
6
+ import { newerVersion } from "../../semantics/lang.js";
6
7
  /** The member names script reads, writes and calls on `any` values in these files. */
7
8
  export function untypedMembers(checker, files) {
8
9
  const uses = new Map();
@@ -58,7 +59,7 @@ export function nativeDispatch(modules, uses, deploymentTarget, defined = {}, de
58
59
  const hidden = new Map(candidates.filter(({ cls }) => named.get(cls.swift) === 1 && qualified(cls)).map(({ cls }) => [cls.swift, typeName(cls)]));
59
60
  const typed = (type) => (hidden.size ? type.replace(/(?<![\w.])[A-Z]\w*/g, (n) => hidden.get(n) ?? n) : type);
60
61
  const gets = [], sets = [], calls = [];
61
- const guarded = (introduced, code) => (introduced && newer(introduced, deploymentTarget) ? `if #available(iOS ${introduced}, *) { ${code} }` : code);
62
+ const guarded = (introduced, code) => (introduced && newerVersion(introduced, deploymentTarget) ? `if #available(iOS ${introduced}, *) { ${code} }` : code);
62
63
  for (const [name, u] of [...uses].sort(([a], [b]) => compareText(a, b))) {
63
64
  const get = [], set = [], call = [];
64
65
  for (const { js, cls } of candidates) {
@@ -209,10 +210,3 @@ function fromNative(code, type) {
209
210
  return `${code} as Any?`;
210
211
  return `${RT.jsNativeResult}(${code})`;
211
212
  }
212
- function newer(version, than) {
213
- const a = version.split('.').map(Number), b = than.split('.').map(Number);
214
- for (let i = 0; i < Math.max(a.length, b.length); i++)
215
- if ((a[i] ?? 0) !== (b[i] ?? 0))
216
- return (a[i] ?? 0) > (b[i] ?? 0);
217
- return false;
218
- }
@@ -16,8 +16,19 @@ export const objectClassesMethods = {
16
16
  // A view keeps no fields: each reads and writes its root's key, and its own object's fields are `jsOwn`'s. A result
17
17
  // interface's class in the kit has one for an app's untyped object of it.
18
18
  const view = !symbolic.length && !keyed.length && (this.library ? resultShapeNamed(this, name) : this.viewed.has(name));
19
+ // Fast direct JSON writer for plain shapes (no views, symbols, Any, functions, BigInt, or declared toJSON).
20
+ const fastJSON = !this.library &&
21
+ !view &&
22
+ !symbolic.length &&
23
+ !keyed.length &&
24
+ fields.length > 0 &&
25
+ !fields.some((f) => {
26
+ const h = this.shapeHeld(f);
27
+ const base = h.replace(/[?!]$/, '');
28
+ return f.name === 'toJSON' || base === 'Any' || isFunctionType(base.replace(/^\((.*)\)$/, '$1')) || /^JS(Nullish|BigInt)\b/.test(base);
29
+ });
19
30
  this.shapesWritten.add(name);
20
- const lines = [`final class ${name}: ${['JSDynamic', ...this.shapeProtocols(allFields).map((x) => x.conformance), ...(symbolic.length ? [] : ['JSObjectConvertible']), ...(view ? ['JSViewing'] : []), ...(keyed.length ? ['JSSymbolKeyed'] : [])].join(', ')} {`, NONISOLATED_DEINIT];
31
+ const lines = [`final class ${name}: ${['JSDynamic', ...this.shapeProtocols(allFields).map((x) => x.conformance), ...(symbolic.length ? [] : ['JSObjectConvertible']), ...(fastJSON ? ['JSJSONFastSerializable'] : []), ...(view ? ['JSViewing'] : []), ...(keyed.length ? ['JSSymbolKeyed'] : [])].join(', ')} {`, NONISOLATED_DEINIT];
21
32
  const held = (f) => this.shapeHeld(f);
22
33
  // A field the object lacks, or holds of another type (JSON without an optional field), reads as JavaScript converts it where used.
23
34
  const fieldType = (f) => (this.lenient ? held(f).replace(/^\((.*)\)!$/, '($1)?') : held(f).endsWith('!') ? optionalType(f.type) : f.type);
@@ -109,6 +120,78 @@ export const objectClassesMethods = {
109
120
  }
110
121
  members[0] = ` var jsKeys: [String] {\n${view ? ' if let __r = jsRoot { return __r.jsKeys }\n' : ''} let order = jsOrder ?? ${declared}\n let keys = order + (jsExtra?.jsKeys ?? []).filter { !order.contains($0) }\n return ${optional.length ? 'keys.filter(jsHas)' : 'keys'}\n }`;
111
122
  lines.push(...members);
123
+ if (fastJSON) {
124
+ const canFast = ['jsOrder == nil', 'jsExtra == nil', ...(nullable.length ? ['jsNulls == nil'] : []), ...(optional.length ? ['jsUnset == nil'] : [])].join(' && ');
125
+ const safe = (f) => ['Double', 'String', 'Bool'].includes(this.shapeHeld(f));
126
+ const guaranteedFirst = safe(fields[0]);
127
+ const steps = [];
128
+ if (guaranteedFirst) {
129
+ fields.forEach((f, idx) => {
130
+ const h = this.shapeHeld(f);
131
+ const opt = h.endsWith('?');
132
+ const base = h.replace(/[?!]$/, '');
133
+ const ref = `self.${ident(memberOf(f))}`;
134
+ const keyLit = JSON.stringify(f.name);
135
+ const prefix = idx === 0 ? `{${keyLit}:` : `,${keyLit}:`;
136
+ if (!opt && h === 'Double')
137
+ steps.push(` out.appendJSONLiteral(${swiftString(prefix)}); out.appendJSONNumber(${ref})`);
138
+ else if (!opt && h === 'String')
139
+ steps.push(` out.appendJSONLiteral(${swiftString(prefix)}); out.appendJSONString(${ref})`);
140
+ else if (!opt && h === 'Bool')
141
+ steps.push(` out.appendJSONLiteral(${swiftString(prefix)}); out.appendJSONBool(${ref})`);
142
+ else if (opt && base === 'Double')
143
+ steps.push(` if let __v = ${ref} { out.appendJSONLiteral(${swiftString(prefix)}); out.appendJSONNumber(__v) }`);
144
+ else if (opt && base === 'String')
145
+ steps.push(` if let __v = ${ref} { out.appendJSONLiteral(${swiftString(prefix)}); out.appendJSONString(__v) }`);
146
+ else if (opt && base === 'Bool')
147
+ steps.push(` if let __v = ${ref} { out.appendJSONLiteral(${swiftString(prefix)}); out.appendJSONBool(__v) }`);
148
+ else if (base === 'JSArray<Double>')
149
+ steps.push(` if !out.appendJSONNumbersIfPlain(${swiftString(prefix)}, ${ref}) { try writeField(${swiftString(prefix)}, ${swiftString(f.name)}, ${ref}) }`);
150
+ else if (base === 'JSArray<String>')
151
+ steps.push(` if !out.appendJSONStringsIfPlain(${swiftString(prefix)}, ${ref}) { try writeField(${swiftString(prefix)}, ${swiftString(f.name)}, ${ref}) }`);
152
+ else
153
+ steps.push(` try writeField(${swiftString(prefix)}, ${swiftString(f.name)}, ${ref})`);
154
+ });
155
+ steps.push(' out.appendJSONLiteral("}")');
156
+ }
157
+ else {
158
+ steps.push(' out.appendJSONLiteral("{")');
159
+ steps.push(' var __first = true');
160
+ const needsMark = fields.some((f) => !['Double', 'String', 'Bool'].includes(this.shapeHeld(f).replace(/\?$/, '')));
161
+ if (needsMark)
162
+ steps.push(' var __m = 0');
163
+ for (const f of fields) {
164
+ const h = this.shapeHeld(f);
165
+ const opt = h.endsWith('?');
166
+ const base = h.replace(/[?!]$/, '');
167
+ const ref = `self.${ident(memberOf(f))}`;
168
+ const keyLit = JSON.stringify(f.name);
169
+ const p0 = `${keyLit}:`;
170
+ const p1 = `,${keyLit}:`;
171
+ const pExpr = `__first ? ${swiftString(p0)} : ${swiftString(p1)}`;
172
+ if (!opt && h === 'Double')
173
+ steps.push(` out.appendJSONLiteral(${pExpr}); out.appendJSONNumber(${ref}); __first = false`);
174
+ else if (!opt && h === 'String')
175
+ steps.push(` out.appendJSONLiteral(${pExpr}); out.appendJSONString(${ref}); __first = false`);
176
+ else if (!opt && h === 'Bool')
177
+ steps.push(` out.appendJSONLiteral(${pExpr}); out.appendJSONBool(${ref}); __first = false`);
178
+ else if (opt && base === 'Double')
179
+ steps.push(` if let __v = ${ref} { out.appendJSONLiteral(${pExpr}); out.appendJSONNumber(__v); __first = false }`);
180
+ else if (opt && base === 'String')
181
+ steps.push(` if let __v = ${ref} { out.appendJSONLiteral(${pExpr}); out.appendJSONString(__v); __first = false }`);
182
+ else if (opt && base === 'Bool')
183
+ steps.push(` if let __v = ${ref} { out.appendJSONLiteral(${pExpr}); out.appendJSONBool(__v); __first = false }`);
184
+ else if (base === 'JSArray<Double>')
185
+ steps.push(` __m = out.count; if !out.appendJSONNumbersIfPlain(${pExpr}, ${ref}) { try writeField(${pExpr}, ${swiftString(f.name)}, ${ref}) }; if out.count != __m { __first = false }`);
186
+ else if (base === 'JSArray<String>')
187
+ steps.push(` __m = out.count; if !out.appendJSONStringsIfPlain(${pExpr}, ${ref}) { try writeField(${pExpr}, ${swiftString(f.name)}, ${ref}) }; if out.count != __m { __first = false }`);
188
+ else
189
+ steps.push(` __m = out.count; try writeField(${pExpr}, ${swiftString(f.name)}, ${ref}); if out.count != __m { __first = false }`);
190
+ }
191
+ steps.push(' out.appendJSONLiteral("}")');
192
+ }
193
+ lines.push(` var jsCanFastJSON: Bool { ${canFast} }`, ' func jsWriteJSONFast(to out: JSUTF8Buffer, writeField: (StaticString, String, Any?) throws -> Void) throws -> Bool {', ' if !jsCanFastJSON { return false }', ...steps, ' return true', ' }');
194
+ }
112
195
  lines.push('}');
113
196
  return lines.join('\n');
114
197
  },
@@ -12,6 +12,7 @@ import { constClassExpr, hasInstanceClass } from "../semantics/classes.js";
12
12
  import { isUntyped, spelledType } from "../semantics/types.js";
13
13
  import { bigIntArithmetic, bigIntCompare, bigIntPlan } from "../semantics/apis/bigint.js";
14
14
  import { BIT_ASSIGNMENTS, addCall, bitOperation, concatOperand, numericThrowing, untypedBinary, untypedConversion } from "../semantics/apis/operators.js";
15
+ import { planArithmetic, planEquality, planLogicalAssign, planRelational, typeofComparison } from "../semantics/lower.js";
15
16
  /** BigInt's operations the backend spells as an operator. */
16
17
  const BIGINT_INFIX = { add: '+', subtract: '-', multiply: '*', and: '&', or: '|', xor: '^' };
17
18
  export const operatorsMethods = {
@@ -125,29 +126,32 @@ export const operatorsMethods = {
125
126
  return assigned(() => `${l()} ?? ${(isOptional(this.declaredTypeOf(e.left) ?? this.typeOf(e.left)) ? this.maybeUndefined(e.right) : null) ?? this.stored(e.right, e.left, this.typeOf(e.left).replace(/\?$/, ''))}`);
126
127
  return this.marks.blockCode(`if ${this.tryPrefix(e.left)}${RT.jsIsNullish}(${l()}) { ${this.tryPrefix(e.right)}${target()} = ${(isOptional(this.declaredTypeOf(e.left) ?? this.typeOf(e.left)) ? this.maybeUndefined(e.right) : null) ?? this.stored(e.right, e.left, this.typeOf(e.left).replace(/\?$/, ''))} }`);
127
128
  case K.BarBarEqualsToken:
128
- return this.marks.blockCode(`if !${RT.jsTruthy}(${this.tryPrefix(e.left)}${l()}) { ${this.tryPrefix(e)}${target()} = ${this.stored(e.right, e.left, this.typeOf(e.left))} }`);
129
- case K.AmpersandAmpersandEqualsToken:
130
- return this.marks.blockCode(`if ${RT.jsTruthy}(${this.tryPrefix(e.left)}${l()}) { ${this.tryPrefix(e)}${target()} = ${this.stored(e.right, e.left, this.typeOf(e.left))} }`);
131
- case K.PlusToken: {
132
- if (this.isString(e.left) || this.isString(e.right))
133
- return this.marks.infix(concatOperand(this, e.left, untyped), '+', concatOperand(this, e.right, untyped));
134
- if (this.isAny(e.left) || this.isAny(e.right)) {
135
- const sum = addCall(this, e, untyped), t = this.typeOf(e);
136
- return isUntyped(spelledType(t)) ? sum : this.fromAnyCode(sum, t);
137
- }
138
- return this.marks.infix(this.toNumber(e.left), '+', this.toNumber(e.right));
129
+ case K.AmpersandAmpersandEqualsToken: {
130
+ const plan = planLogicalAssign(op);
131
+ return this.marks.blockCode(`if ${plan.op === '||=' ? '!' : ''}${RT.jsTruthy}(${this.tryPrefix(e.left)}${l()}) { ${this.tryPrefix(e)}${target()} = ${this.stored(e.right, e.left, this.typeOf(e.left))} }`);
139
132
  }
133
+ case K.PlusToken:
140
134
  case K.MinusToken:
141
- return this.marks.infix(this.toNumber(e.left), '-', this.toNumber(e.right));
142
135
  case K.AsteriskToken:
143
- return this.marks.infix(this.toNumber(e.left), '*', this.toNumber(e.right));
144
- // Integer literals on both sides would divide as Int where no operand pins Double (`Double(1 / 8)`, `js(16 / 9)`).
145
136
  case K.SlashToken:
146
- return numericLiteralOnly(e.left) && numericLiteralOnly(e.right) ? `(${this.expr(e.left)} as Double) / ${this.expr(e.right)}` : this.marks.infix(this.toNumber(e.left), '/', this.toNumber(e.right));
147
137
  case K.PercentToken:
148
- return `${RT.jsMod}(${this.toNumber(e.left)}, ${this.toNumber(e.right)})`;
149
- case K.AsteriskAsteriskToken:
150
- return `${RT.jsPow}(${this.toNumber(e.left)}, ${this.toNumber(e.right)})`;
138
+ case K.AsteriskAsteriskToken: {
139
+ const plan = planArithmetic(op, this.isString(e.left), this.isString(e.right), this.isAny(e.left), this.isAny(e.right));
140
+ if (plan.kind === 'concat')
141
+ return this.marks.infix(concatOperand(this, e.left, untyped), '+', concatOperand(this, e.right, untyped));
142
+ if (plan.kind === 'dynamicAdd') {
143
+ const sum = addCall(this, e, untyped), t = this.typeOf(e);
144
+ return isUntyped(spelledType(t)) ? sum : this.fromAnyCode(sum, t);
145
+ }
146
+ // Integer literals on both sides would divide as Int where no operand pins Double (`Double(1 / 8)`, `js(16 / 9)`).
147
+ if (plan.op === '/' && numericLiteralOnly(e.left) && numericLiteralOnly(e.right))
148
+ return `(${this.expr(e.left)} as Double) / ${this.expr(e.right)}`;
149
+ if (plan.op === '%')
150
+ return `${RT.jsMod}(${this.toNumber(e.left)}, ${this.toNumber(e.right)})`;
151
+ if (plan.op === '**')
152
+ return `${RT.jsPow}(${this.toNumber(e.left)}, ${this.toNumber(e.right)})`;
153
+ return this.marks.infix(this.toNumber(e.left), plan.op, this.toNumber(e.right));
154
+ }
151
155
  case K.EqualsEqualsEqualsToken:
152
156
  case K.ExclamationEqualsEqualsToken:
153
157
  case K.EqualsEqualsToken:
@@ -157,15 +161,15 @@ export const operatorsMethods = {
157
161
  case K.GreaterThanToken:
158
162
  case K.LessThanEqualsToken:
159
163
  case K.GreaterThanEqualsToken: {
160
- const sym = ts.tokenToString(op);
161
- if (this.isString(e.left) && this.isString(e.right))
162
- return `${RT.jsCompare}(${l()}, ${r()}) ${sym} 0`;
164
+ const plan = planRelational(op, this.isString(e.left), this.isString(e.right), this.isAny(e.left) || this.isAny(e.right));
165
+ if (plan.kind === 'string')
166
+ return `${RT.jsCompare}(${l()}, ${r()}) ${plan.op} 0`;
163
167
  // An untyped side may hold a string, and two strings compare as strings.
164
- if (this.isAny(e.left) || this.isAny(e.right)) {
168
+ if (plan.kind === 'dynamic') {
165
169
  const [a, b] = [this.coerce(e.left, 'Any?'), this.coerce(e.right, 'Any?')];
166
- return op === K.LessThanToken ? `(${RT.jsLessThan}(${a}, ${b}) == true)` : op === K.GreaterThanToken ? `(${RT.jsGreaterThan}(${a}, ${b}) == true)` : op === K.LessThanEqualsToken ? `(${RT.jsGreaterThan}(${a}, ${b}) == false)` : `(${RT.jsLessThan}(${a}, ${b}) == false)`;
170
+ return plan.op === '<' ? `(${RT.jsLessThan}(${a}, ${b}) == true)` : plan.op === '>' ? `(${RT.jsGreaterThan}(${a}, ${b}) == true)` : plan.op === '<=' ? `(${RT.jsGreaterThan}(${a}, ${b}) == false)` : `(${RT.jsLessThan}(${a}, ${b}) == false)`;
167
171
  }
168
- return this.marks.infix(this.toNumber(e.left), sym, this.toNumber(e.right));
172
+ return this.marks.infix(this.toNumber(e.left), plan.op, this.toNumber(e.right));
169
173
  }
170
174
  case K.QuestionQuestionToken: {
171
175
  const t = this.typeOf(e);
@@ -445,24 +449,23 @@ export const operatorsMethods = {
445
449
  * there, a nil check. Null where the test is not one of presence.
446
450
  */
447
451
  typeofPresence(e) {
448
- const strip = (x) => ts.skipOuterExpressions(x, ts.OuterExpressionKinds.Parentheses);
449
- const [l, r] = [strip(e.left), strip(e.right)];
450
- const [t, lit] = ts.isTypeOfExpression(l) && ts.isStringLiteralLike(r) ? [l, r] : ts.isTypeOfExpression(r) && ts.isStringLiteralLike(l) ? [r, l] : [null, null];
451
- if (!t || !lit)
452
+ const cmp = typeofComparison(e);
453
+ if (!cmp)
452
454
  return null;
455
+ const left = ts.skipOuterExpressions(e.left, ts.OuterExpressionKinds.Parentheses);
456
+ const t = (ts.isTypeOfExpression(left) ? left : ts.skipOuterExpressions(e.right, ts.OuterExpressionKinds.Parentheses));
453
457
  const c = this.typeofCell(t);
454
- if (c.cell !== 'presence' || (lit.text !== 'undefined' && lit.text !== c.type))
458
+ if (c.cell !== 'presence' || (cmp.tag !== 'undefined' && cmp.tag !== c.type))
455
459
  return null;
456
- const negate = e.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken || e.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsToken;
457
- return `${c.tested} ${(lit.text === 'undefined') !== negate ? '==' : '!='} nil`;
460
+ return `${c.tested} ${(cmp.tag === 'undefined') !== cmp.negated ? '==' : '!='} nil`;
458
461
  },
459
462
  equality(e) {
460
463
  this.refuseUnheldIdentity(e.left);
461
464
  this.refuseUnheldIdentity(e.right);
462
465
  const K = ts.SyntaxKind;
463
- const op = e.operatorToken.kind;
464
- const negate = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
465
- const strict = op === K.EqualsEqualsEqualsToken || op === K.ExclamationEqualsEqualsToken;
466
+ const eq = planEquality(e.operatorToken.kind, false, false, false, false);
467
+ const negate = eq.negated;
468
+ const strict = eq.kind === 'strict';
466
469
  const isNullish = (x) => x.kind === K.NullKeyword || (ts.isIdentifier(x) && x.text === 'undefined');
467
470
  const [a, b] = [e.left, e.right];
468
471
  const lt = this.typeOf(a);
@@ -379,14 +379,7 @@ export const optionalChainsMethods = {
379
379
  * A string, number or boolean read `e` of type `t` as the optional it holds, where it converts undefined (a read, or
380
380
  * a choice one of whose branches does); null where it converts nothing.
381
381
  */
382
- convertedOptional(e, t) {
383
- if (this.library)
384
- return null;
385
- const inner = ts.skipOuterExpressions(e);
386
- if (ts.isConditionalExpression(inner) && this.typeOf(inner) === t && [inner.whenTrue, inner.whenFalse].some((x) => this.undefinedConverted(this.coerce(ts.skipOuterExpressions(x, ts.OuterExpressionKinds.Parentheses), t))))
387
- return this.coerce(inner, optionalType(t));
388
- return this.undefinedConverted(this.expr(ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses)));
389
- },
382
+ /* convertedOptional is installed from semantics/lowering-methods.ts */
390
383
  /**
391
384
  * App and plugin code's string, number or boolean read that converts undefined (`(x ?? "undefined")`): the optional it
392
385
  * converts, for a use that takes undefined as it is (a comparison). Null for any other code.
@@ -2,7 +2,6 @@
2
2
  import ts from 'typescript';
3
3
  import { assignsTo, ident, isFunctionType, isOptional, nullishType, optionalType, swiftString, RT } from "./syntax.js";
4
4
  import { boundNames, hasModifier } from "../semantics/ast.js";
5
- import { isConstant } from "../semantics/lang.js";
6
5
  import { isUntyped, spelledType } from "../semantics/types.js";
7
6
  export const parametersMethods = {
8
7
  /** A parameter's Swift type as `params` declares it (an unwrapped optional written as optional, as a function type has it). */
@@ -131,9 +130,6 @@ export const parametersMethods = {
131
130
  * A parameter Swift gives its default value itself: a constant, unless the method it overrides takes the parameter as optional.
132
131
  * An untyped one is given its default in the body, where an explicit undefined (nil) takes it too and null does not.
133
132
  */
134
- constantDefault(p) {
135
- return !!p.initializer && isConstant(p.initializer) && !this.optionalDefaults.has(p) && !this.familyDefaultsDiffer(p) && !this.isAny(p.name) && !this.states.defaultTakesUndefined(p);
136
- },
137
133
  /** An app parameter whose default its body applies (`paramPrelude`): an argument is given as the optional it may be. */
138
134
  filledDefault(d) {
139
135
  return !this.library && !!d && ts.isParameter(d) && !!d.initializer && !d.dotDotDotToken && !this.templateParams && !d.getSourceFile().isDeclarationFile && !this.constantDefault(d);
@@ -109,18 +109,7 @@ export const placementMethods = {
109
109
  const t = contextual ? this.type(contextual, e) : ts.isFunctionLike(slot) ? this.returnTypeOf(slot) : ts.isIdentifier(slot.name ?? slot) ? this.typeOf(slot.name) : 'Any?';
110
110
  return !/[?!]$/.test(t);
111
111
  },
112
- /** A `nullishRead` value as its `JSNullish<T>`. */
113
- nullishCode(e) {
114
- if (!ts.isCallExpression(e) && !ts.isPropertyAccessExpression(e))
115
- return this.refName(e);
116
- this.nullishCalls.add(e);
117
- try {
118
- return this.expr(e);
119
- }
120
- finally {
121
- this.nullishCalls.delete(e);
122
- }
123
- },
112
+ /* nullishCode is installed from semantics/lowering-methods.ts */
124
113
  /** An app generic class's instance where the same class with an `any` type argument is wanted: Swift's generic classes are invariant. */
125
114
  checkAnyArgument(e, target) {
126
115
  const want = /^(\w+)<(.+)>[?!]?$/.exec(target);
@@ -250,7 +239,7 @@ export const placementMethods = {
250
239
  if (this.lenient && ts.isIdentifier(e) && !isWriteTarget(e) && !isUntyped(spelledType(target))) {
251
240
  const d = this.resolve(e)?.valueDeclaration;
252
241
  if (d && ts.isVariableDeclaration(d) && !d.type && !d.initializer && isUntyped(spelledType(this.declaredTypeOf(e))) && this.typeOf(e) !== target) {
253
- const read = this.fromAny(this.refName(e), target);
242
+ const read = this.throwingConverts(() => this.fromAny(this.refName(e), target), this.libraryThrowsHere(e), e);
254
243
  return this.nullableRef(target) !== target && !this.looseTolerated(e) ? this.presentCode(read, target) : read;
255
244
  }
256
245
  }
@@ -310,7 +299,7 @@ export const placementMethods = {
310
299
  return unwrap?.op !== 'unwrap' || !postfixChain(unwrap.of.code) ? code : c?.op === 'try' ? this.marks.tryCode(unwrap.of.code) : unwrap.of.code;
311
300
  },
312
301
  coerced(e, target) {
313
- if (this.isComputedProperty(e) && /^Signal<.*>[?!]?$/.test(target)) {
302
+ if (this.isSwiftComputedProperty(e) && /^Signal<.*>[?!]?$/.test(target)) {
314
303
  const inner = target.replace(/[?!]$/, '').slice(7, -1);
315
304
  return `Signal<${inner}>(computing: { ${this.marks.tryBefore(this.tryPrefix(e), this.coerce(e, inner))} })`;
316
305
  }
@@ -395,7 +384,8 @@ export const placementMethods = {
395
384
  // An array literal where any value may go holds any value: script may store a string in `const list: any = [1, 2]`,
396
385
  // or in `{ list: [1] }` of an untyped object.
397
386
  const untypedMember = ts.isPropertyAssignment(bare.parent) && this.dynamicLiterals.has(bare.parent.parent);
398
- if (ts.isArrayLiteralExpression(bare) && isUntyped(spelledType(target)) && !ts.isAsExpression(e) && (untypedMember || !!(this.checker.getContextualType(bare)?.flags & ts.TypeFlags.Any)))
387
+ const ctx = this.checker.getContextualType(bare);
388
+ if (ts.isArrayLiteralExpression(bare) && isUntyped(spelledType(target)) && !ts.isAsExpression(e) && ((untypedMember && (!ctx || !!(ctx.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) || !this.checker.isArrayType(ctx))) || !!(ctx?.flags & ts.TypeFlags.Any)))
399
389
  return this.array(bare, 'JSArray<Any?>');
400
390
  // An array of tuples where the slot's type has them typed (`[[property, color]]` for `[any, any][]` returned as `[CssProperty, Color][]`).
401
391
  const tuples = /^(JSArray<)?(\(.*\))>?$/.exec(target.replace(/\?$/, ''));
@@ -129,10 +129,6 @@ export const resultsMethods = {
129
129
  }
130
130
  return this.undefinedAs(slot.raw, t, slot.target);
131
131
  },
132
- /** The slot of the await `e` is, where its continuation holds the value optional. */
133
- awaited(e) {
134
- return this.awaitSlots.get(ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses));
135
- },
136
132
  /** A local Swift holds optional though its type says a value (`const x = f()` of a call that may give nothing). */
137
133
  heldOptionalLocal(e, type) {
138
134
  e = ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses);
@@ -62,7 +62,7 @@ export const stateBackendMethods = {
62
62
  return t.library;
63
63
  },
64
64
  get native() {
65
- return t.native;
65
+ return { holdsNil: (d) => t.native.iosHoldsNil(d) };
66
66
  },
67
67
  get framework() {
68
68
  return t.framework;
@@ -86,7 +86,8 @@ export const stateBackendMethods = {
86
86
  return heldAs(t, isOptional(t) || t.endsWith('!'));
87
87
  },
88
88
  declaredOptional: (x) => this.declaredOptional(x),
89
- kitNil: (x) => !this.library && this.core.kitNil(x),
89
+ kitNil: (x) => !this.library && this.core.swiftKitNil(x),
90
+ untypedCastChecks: (e, t) => !this.lenient && this.isObjectRef(e) && this.castChecks(spell(t)),
90
91
  keyedClass: (c) => keyedClass(c, this.states, this.shapeFacts()),
91
92
  };
92
93
  },
@@ -182,19 +182,7 @@ export const statementsMethods = {
182
182
  });
183
183
  return forward;
184
184
  },
185
- block(b, base) {
186
- if (base === undefined)
187
- base = this.indent;
188
- const saved = this.indent;
189
- this.indent = base + ' ';
190
- try {
191
- const body = this.statements(ts.isBlock(b) ? [...b.statements] : [b]);
192
- return `{\n${body.join('\n')}\n${base}}`;
193
- }
194
- finally {
195
- this.indent = saved;
196
- }
197
- },
185
+ /* block is installed from semantics/lowering-methods.ts */
198
186
  stmt(s) {
199
187
  try {
200
188
  return HELD_LOSS ? atLossSite('swift', this, s, () => this.stmtChecked(s)) : this.stmtChecked(s);
@@ -16,7 +16,6 @@ export const staticCallsMethods = {
16
16
  if (!s)
17
17
  throw this.error(e, `${owner}.${member}`, 'library-member');
18
18
  const method = s.name;
19
- const a = () => this.args(e);
20
19
  const arg = (k) => e.arguments[k];
21
20
  const T = () => this.typeOf(e);
22
21
  if (TYPED_ARRAYS.includes(owner) && (method === 'of' || method === 'from')) {
@@ -134,7 +133,7 @@ export const staticCallsMethods = {
134
133
  if (method === 'from' && (e.arguments.length === 2 || e.arguments.length === 3))
135
134
  return this.ignoringThisArg(e, arg(0), () => `JSArray<${this.elementTypeOf(arg(0))}>.from(${this.iterable(arg(0))}).map(${this.expr(arg(1))})`);
136
135
  if (method === 'of')
137
- return `${T()}([${a().join(', ')}])`;
136
+ return e.arguments.some(ts.isSpreadElement) ? this.packed(e.arguments, T()) : `${T()}([${e.arguments.map((x) => this.restArgument(e, x, T().replace(/^JSArray<(.*)>$/, '$1'))).join(', ')}])`;
138
137
  // `Array.apply(thisArg, list)`: `Array(...list)`, a length when the list is one number.
139
138
  if (method === 'apply' && e.arguments.length === 2) {
140
139
  const made = `${RT.jsArrayConstruct}(${this.restArgument(e, arg(1), 'JSArray<Any?>')}.storage)`;
@@ -167,7 +166,7 @@ export const staticCallsMethods = {
167
166
  if (method === 'fromCharCode' && e.arguments.some(ts.isSpreadElement))
168
167
  return `${RT.jsFromCharCode}(codes: ${this.packed(e.arguments, 'JSArray<Double>')}.storage)`;
169
168
  if (method === 'fromCharCode')
170
- return `${RT.jsFromCharCode}(${a().join(', ')})`;
169
+ return `${RT.jsFromCharCode}(${e.arguments.map((x) => this.restArgument(e, x, 'Double')).join(', ')})`;
171
170
  if (method === 'fromCodePoint' && e.arguments.some(ts.isSpreadElement))
172
171
  return `${RT.jsFromCodePoint}(codes: ${this.packed(e.arguments, 'JSArray<Double>')}.storage)`;
173
172
  if (method === 'fromCodePoint')