@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
package/README.md CHANGED
@@ -3,9 +3,12 @@
3
3
  NativeScript CLI extension (`ns compile`) that compiles NativeScript apps directly to native Swift (iOS) and Kotlin (Android) with no JavaScript runtime.
4
4
 
5
5
  - **No JavaScript engine in release builds.** App TypeScript, npm dependencies, and `@nativescript/core` compile directly to Swift and Kotlin and are built with Xcode and Gradle.
6
+ - **Direct, deterministic native platform APIs.** Unlike JS-to-native compilers that stall behind untyped bridges or restricted dialects, NativeScript's 1:1 TypeScript platform declarations (`@nativescript/types-ios` and `@nativescript/types-android`) let the compiler resolve UIKit, Foundation, and Android SDK classes, overloads, protocols, and subclasses deterministically at compile time — emitting direct Swift and Kotlin calls with no C ABI or JNI hop.
6
7
  - **Source-mapped crash traces.** Generated native code preserves TypeScript source lines so release stack traces resolve back to your app source via `ns compile retrace`.
7
8
  - **NativeScriptKit built from `@nativescript/core`.** Views, layout, and CSS are compiled from `@nativescript/core` and linked natively.
8
9
 
10
+ See [Why NativeScript Makes This Possible](https://github.com/nstudio/nativescript-compiler/blob/main/README.md#why-nativescript-makes-this-possible) and [ARCHITECTURE.md](https://github.com/nstudio/nativescript-compiler/blob/main/packages/compiler/docs/ARCHITECTURE.md#related-work-and-why-swift-and-kotlin-source) for how this compares with prior AOT JS/TS compilers.
11
+
9
12
  ## Requirements
10
13
 
11
14
  - Node.js `>= 20.17.0`
@@ -9,8 +9,8 @@ import { mathFunctionValue } from "../semantics/apis/math.js";
9
9
  import { CONSOLE } from "../semantics/apis/console.js";
10
10
  import { libFunctionValueKind } from "../semantics/apis/statics.js";
11
11
  import { ERRORS, isLibGlobal } from "../semantics/globals.js";
12
- import { spell, ident, isCompared, isNullable, isThisParameter, kotlinString, numberLiteral, optionalType, testsMissing, scriptPrimitive, RT, assertedReader } from "./syntax.js";
13
- import { receiverCell, receiverSlot, isEnumObject, nullishField } from "../semantics/placement.js";
12
+ import { ident, isCompared, isNullable, isThisParameter, kotlinString, numberLiteral, optionalType, testsMissing, scriptPrimitive, RT, assertedReader } from "./syntax.js";
13
+ import { elementReceiverCell, keyName, receiverCell, receiverSlot, isEnumObject, nullishField } from "../semantics/placement.js";
14
14
  import { accessedDeclaration, augmentedPropertyRead, functionProperty, wellKnownMember, isSelf, literalMethod, uncheckedMatch } from "../semantics/lang.js";
15
15
  import { convertedRead, onlyNull } from "../semantics/states/predicates.js";
16
16
  import { isLibDeclaration, isWriteTarget, notIterable } from "../semantics/ast.js";
@@ -528,6 +528,12 @@ export const accessMethods = {
528
528
  const rt = this.typeOf(e);
529
529
  if (t === 'JSArray<Any?>' && !isUntyped(spelledType(rt)))
530
530
  return this.fromAny(this.maybeUndefined(e), rt);
531
+ if (t === 'JSArray<Double>' && rt === 'Double' && !q && !(e.flags & ts.NodeFlags.OptionalChain) && (!this.typeOf(e.expression).endsWith('?') || !this.library)) {
532
+ const cell = elementReceiverCell(this.receivers, e);
533
+ const missing = !this.library && this.typeOf(e.expression).endsWith('?');
534
+ const recv = cell.cell === 'present' ? this.receiverCode(cell, keyName(key)) : missing ? this.present(target, key, e.expression) : target;
535
+ return `${recv}.numberAt(${this.toNumber(key)})`;
536
+ }
531
537
  return this.undefinedAs(this.maybeUndefined(e), rt);
532
538
  }
533
539
  if (t === 'JSMatch') {
@@ -595,11 +601,6 @@ export const accessMethods = {
595
601
  }
596
602
  throw this.error(e, 'indexing this type', 'index-type');
597
603
  },
598
- /** `assertedUntyped`'s cast: to an object type other than the kit's own containers, promises, dates and errors. */
599
- untypedCastChecks(_e, t) {
600
- const type = spell(t);
601
- return this.isObjectType(type) && !/^JS(Array|Record|Promise|Date|Error)\b/.test(type);
602
- },
603
604
  /** An `assertedUntyped` assertion read as the nullable it may be: null where the value is undefined or null. */
604
605
  /** `x as Iterable<T>` of a value not held as one: whatever x holds iterated, as GetIterator does where it is iterated. */
605
606
  iterableCast(e) {
@@ -2,13 +2,14 @@
2
2
  import ts from 'typescript';
3
3
  import { TYPED_ARRAYS } from "../semantics/globals.js";
4
4
  import { functionTypeParts, ident, isNullable, kotlinString, lambda, negated, setterMethod, RT } from "./syntax.js";
5
- import { asOperation } from "../semantics/lang.js";
5
+ import { asOperation, unsafeReceiver } from "../semantics/lang.js";
6
6
  import { notedField } from "../semantics/shapes.js";
7
7
  import { isNamed, isUntyped, spelledType } from "../semantics/types.js";
8
8
  import { assignedTo, negatedCell } from "../semantics/placement.js";
9
9
  import { isStatic } from "../semantics/throws.js";
10
10
  import { symbolField, isPromiseType } from "../semantics/spelled.js";
11
11
  import { untypedUnary } from "../semantics/apis/operators.js";
12
+ import { planUnary } from "../semantics/lower.js";
12
13
  export const assignmentMethods = {
13
14
  /** The 1 that `++` and `--` step a number or a BigInt by. */
14
15
  one(e) {
@@ -19,19 +20,24 @@ export const assignmentMethods = {
19
20
  const thrown = untypedUnary(this, e);
20
21
  if (thrown)
21
22
  return thrown;
22
- switch (e.operator) {
23
- case K.ExclamationToken: {
24
- const cell = negatedCell(this.conditions, e.operand);
25
- return negated(cell.step === 'bool' ? this.expr(cell.e) : this.cond(e.operand, cell));
23
+ const unary = planUnary(e.operator, this.typeOf(e.operand) === 'JSBigInt');
24
+ if (unary) {
25
+ switch (unary.kind) {
26
+ case 'not': {
27
+ const cell = negatedCell(this.conditions, e.operand);
28
+ return negated(cell.step === 'bool' ? this.expr(cell.e) : this.cond(e.operand, cell));
29
+ }
30
+ case 'negate':
31
+ if (unary.bigInt)
32
+ return `(-${this.expr(e.operand)})`;
33
+ return ts.isNumericLiteral(e.operand) ? `-${this.expr(e.operand)}` : `-(${this.toNumber(e.operand)})`;
34
+ case 'plus':
35
+ return this.toNumber(e.operand);
36
+ case 'bitNot':
37
+ return unary.bigInt ? `${this.expr(e.operand)}.inv()` : `${RT.jsBitNot}(${this.toNumber(e.operand)})`;
26
38
  }
27
- case K.MinusToken:
28
- if (this.typeOf(e.operand) === 'JSBigInt')
29
- return `(-${this.expr(e.operand)})`;
30
- return ts.isNumericLiteral(e.operand) ? `-${this.expr(e.operand)}` : `-(${this.toNumber(e.operand)})`;
31
- case K.PlusToken:
32
- return this.toNumber(e.operand);
33
- case K.TildeToken:
34
- return this.typeOf(e.operand) === 'JSBigInt' ? `${this.expr(e.operand)}.inv()` : `${RT.jsBitNot}(${this.toNumber(e.operand)})`;
39
+ }
40
+ switch (e.operator) {
35
41
  case K.PlusPlusToken:
36
42
  case K.MinusMinusToken: {
37
43
  const sign = e.operator === K.PlusPlusToken ? '+' : '-';
@@ -224,6 +230,9 @@ export const assignmentMethods = {
224
230
  return `${RT.jsSet}(${this.expr(left.expression)}, ${this.propertyKey(left.argumentExpression)}, ${this.stored(right, left, 'Any?', checks)})`;
225
231
  }
226
232
  const element = ts.isElementAccessExpression(left) && this.states.nullishElements(left.expression) ? this.elementTypeOf(left.expression) : null;
233
+ if (ts.isElementAccessExpression(left) && !element && !left.questionDotToken && !(left.flags & ts.NodeFlags.OptionalChain) && this.typeOf(left.expression) === 'JSArray<Double>' && !this.states.heldOptional(left.expression) && !unsafeReceiver(left.expression, this.checker)) {
234
+ return `${this.expr(left.expression)}.setDouble(${this.toNumber(left.argumentExpression)}, ${this.stored(right, left, 'Double', checks)})`;
235
+ }
227
236
  return `${this.lvalue(left)} = ${this.stored(right, left, element ?? this.declaredTypeOf(left) ?? this.typeOf(left), checks)}`;
228
237
  },
229
238
  };
@@ -103,6 +103,11 @@ export const builtinMethods = {
103
103
  .replace(/^JSArray<(.*)>$/, '$1')));
104
104
  switch (arrayMember(name)?.op) {
105
105
  case 'push':
106
+ if (e.arguments.some(ts.isSpreadElement))
107
+ return `${t}.pushAll(${this.packed(e.arguments, `JSArray<${element}>`, this.elementSlot(e, element))})`;
108
+ if (element === 'Double' && !q && e.arguments.length === 1)
109
+ return `${t}.pushDouble(${this.elementArgument(e, e.arguments[0], 'Double')})`;
110
+ return `${t}.push(${e.arguments.map((x) => this.elementArgument(e, x, element)).join(', ')})`;
106
111
  case 'unshift':
107
112
  if (e.arguments.some(ts.isSpreadElement))
108
113
  return `${t}.${name}All(${this.packed(e.arguments, `JSArray<${element}>`, this.elementSlot(e, element))})`;
@@ -209,6 +214,12 @@ export const builtinMethods = {
209
214
  !!out &&
210
215
  literalCallback(params.map((p) => spelledType(p)), f.parameters.filter((q) => !isThisParameter(q)).map((p) => spelledType(this.paramType(p)))) === 'adapt';
211
216
  const slot = ret || adapts ? `(${params.join(', ')}) -> ${ret ?? out}` : undefined;
217
+ if (element === 'Double' && !q && literal && arity === 1 && !adapted && this.thisArgUse(e, target).kind === 'plain') {
218
+ if (name === 'map' && out === 'Double')
219
+ return `${t}.mapDouble(${this.fn(f, '(Double) -> Double')})`;
220
+ if (name === 'filter')
221
+ return `${t}.filterDouble(${this.fn(f, '(Double) -> Boolean')})`;
222
+ }
212
223
  const code = this.ignoringThisArg(e, target, () => `${t}.${name}(${this.fn(f, slot)})`);
213
224
  // A type-guard filter or find (`(s): s is Circle => …`): its elements as the guard narrows them.
214
225
  const own = this.typeOf(e);
@@ -219,6 +230,8 @@ export const builtinMethods = {
219
230
  return code;
220
231
  }
221
232
  case 'sort':
233
+ if (element === 'Double' && !q && e.arguments[0] && (ts.isArrowFunction(e.arguments[0]) || ts.isFunctionExpression(e.arguments[0])))
234
+ return `${t}.sortDouble(${this.fn(e.arguments[0], '(Double, Double) -> Double')})`;
222
235
  return e.arguments[0] ? `${t}.sort(${this.fn(e.arguments[0], `(${element}, ${element}) -> Double`)})` : `${t}.sort()`;
223
236
  case 'toSorted':
224
237
  return e.arguments[0] ? `${t}.toSorted(${this.fn(e.arguments[0], `(${element}, ${element}) -> Double`)})` : `${t}.toSorted()`;
@@ -254,6 +267,12 @@ export const builtinMethods = {
254
267
  literalCallback(types(acc).map((p) => spelledType(p)), f.parameters.map((p) => spelledType(this.paramType(p)))) === 'adapt'
255
268
  ? `<${acc}>`
256
269
  : '';
270
+ if (element === 'Double' && !q && name === 'reduce' && literal && arity <= 2 && acc === 'Double' && !adapted) {
271
+ const fused = this.fusedDoubleReduce(target, f, init);
272
+ if (fused)
273
+ return fused;
274
+ return `${t}.reduceDouble(${this.fn(f, '(Double, Double) -> Double')}, ${this.coerce(init, 'Double')})`;
275
+ }
257
276
  return `${t}.${name}${named}(${adapted ?? this.fn(f, `(${types(acc).join(', ')}) -> ${acc}`)}, ${this.coerce(init, acc)})`;
258
277
  }
259
278
  return `${t}.${name}(${this.fn(f, `(${this.library ? types(element).join(', ') : `${element}, ${element}`}) -> ${element}`)})`;
@@ -261,6 +280,54 @@ export const builtinMethods = {
261
280
  }
262
281
  throw this.error(e, `Array.${name}`);
263
282
  },
283
+ /** Fuses pure `number[].map(...).filter(...).reduce(...)` (or `.map().reduce()` / `.filter().reduce()`) into a single allocation-free loop. */
284
+ fusedDoubleReduce(target, reducer, init) {
285
+ const pureExpr = (n) => {
286
+ if (ts.isIdentifier(n) || ts.isNumericLiteral(n) || n.kind === ts.SyntaxKind.TrueKeyword || n.kind === ts.SyntaxKind.FalseKeyword)
287
+ return true;
288
+ if (ts.isParenthesizedExpression(n))
289
+ return pureExpr(n.expression);
290
+ if (ts.isPrefixUnaryExpression(n) && [ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.ExclamationToken, ts.SyntaxKind.TildeToken].includes(n.operator))
291
+ return pureExpr(n.operand);
292
+ if (ts.isBinaryExpression(n)) {
293
+ const k = n.operatorToken.kind;
294
+ if (k >= ts.SyntaxKind.FirstAssignment && k <= ts.SyntaxKind.LastAssignment)
295
+ return false;
296
+ return pureExpr(n.left) && pureExpr(n.right);
297
+ }
298
+ if (ts.isConditionalExpression(n))
299
+ return pureExpr(n.condition) && pureExpr(n.whenTrue) && pureExpr(n.whenFalse);
300
+ return false;
301
+ };
302
+ const pureUnary = (fn) => !!fn && ts.isArrowFunction(fn) && !ts.isBlock(fn.body) && fn.parameters.filter((p) => !isThisParameter(p)).length === 1 && pureExpr(fn.body);
303
+ const stage = (expr, method) => {
304
+ const call = ts.skipParentheses(expr);
305
+ if (!ts.isCallExpression(call) || call.questionDotToken || call.arguments.length !== 1)
306
+ return null;
307
+ if (!ts.isPropertyAccessExpression(call.expression) || call.expression.questionDotToken || call.expression.name.text !== method)
308
+ return null;
309
+ const base = call.expression.expression;
310
+ if (this.typeOf(base) !== 'JSArray<Double>' || this.states.heldOptional(base))
311
+ return null;
312
+ if (this.thisArgUse(call, base).kind !== 'plain')
313
+ return null;
314
+ const fn = call.arguments[0];
315
+ return pureUnary(fn) ? { base, fn } : null;
316
+ };
317
+ const fStage = stage(target, 'filter');
318
+ if (fStage) {
319
+ const mStage = stage(fStage.base, 'map');
320
+ if (mStage) {
321
+ return `${this.expr(mStage.base)}.mapFilterReduceDouble(${this.fn(mStage.fn, '(Double) -> Double')}, ${this.fn(fStage.fn, '(Double) -> Boolean')}, ${this.fn(reducer, '(Double, Double) -> Double')}, ${this.coerce(init, 'Double')})`;
322
+ }
323
+ return `${this.expr(fStage.base)}.filterReduceDouble(${this.fn(fStage.fn, '(Double) -> Boolean')}, ${this.fn(reducer, '(Double, Double) -> Double')}, ${this.coerce(init, 'Double')})`;
324
+ }
325
+ const mStage = stage(target, 'map');
326
+ if (mStage) {
327
+ return `${this.expr(mStage.base)}.mapReduceDouble(${this.fn(mStage.fn, '(Double) -> Double')}, ${this.fn(reducer, '(Double, Double) -> Double')}, ${this.coerce(init, 'Double')})`;
328
+ }
329
+ return null;
330
+ },
264
331
  /** A built-in's call taking a callback and a thisArg, made as `thisArgUse` has it; `make` translates it without the thisArg. */
265
332
  ignoringThisArg(e, target, make) {
266
333
  const use = this.thisArgUse(e, target);
@@ -92,7 +92,7 @@ export const callsMethods = {
92
92
  if (!e.arguments.length && callableSignal(this.framework.signalKind(this.symbolName(callee)))) {
93
93
  if (ts.isPropertyAccessExpression(callee) && isSelf(callee.expression, this.subst) && this.props.has(callee.name.text))
94
94
  return `this.${ident(callee.name.text)}.value`;
95
- return this.framework.signalKind(this.symbolName(callee)) === 'computed' && this.isComputedProperty(callee) ? this.expr(callee) : `${this.expr(callee)}.value`;
95
+ return this.framework.signalKind(this.symbolName(callee)) === 'computed' && this.isKotlinComputedProperty(callee) ? this.expr(callee) : `${this.expr(callee)}.value`;
96
96
  }
97
97
  if (callee.kind === ts.SyntaxKind.SuperKeyword)
98
98
  throw this.error(e, 'super() outside the start of a constructor');
@@ -303,7 +303,8 @@ export const callsMethods = {
303
303
  q = '';
304
304
  }
305
305
  if (method === 'fill' && (ts.isNewExpression(target) || ts.isCallExpression(target)) && ts.isIdentifier(target.expression) && target.expression.text === 'Array' && target.arguments?.length === 1 && e.arguments.length === 1) {
306
- return `${RT.jsArrayFilled}<${t.replace(/^JSArray<(.*)>$/, '$1')}>(${this.toNumber(target.arguments[0])}, ${this.coerce(e.arguments[0], t.replace(/^JSArray<(.*)>$/, '$1'))})`;
306
+ const el = t.replace(/^JSArray<(.*)>$/, '$1');
307
+ return el === 'Double' ? `JSArray.doublesFilled(${this.toNumber(target.arguments[0])}, ${this.coerce(e.arguments[0], 'Double')})` : `${RT.jsArrayFilled}<${el}>(${this.toNumber(target.arguments[0])}, ${this.coerce(e.arguments[0], el)})`;
307
308
  }
308
309
  if (method === 'join' && TYPED_ARRAYS.includes(t.replace(/^JS/, '')) && !q && e.arguments.length === 1 && !ts.isSpreadElement(e.arguments[0]))
309
310
  return `${this.expr(target)}.join(${this.joinSeparator(e.arguments[0])})`;
@@ -9,7 +9,7 @@ import { droppedProtocolMemberNames, implementedInterfaces, initializedNull } fr
9
9
  import { hasModifier } from "../semantics/ast.js";
10
10
  import { isStatic } from "../semantics/throws.js";
11
11
  import { isCoreDeclaration, isShimDeclaration } from "../program/core-facts.js";
12
- import { classExprCaptures, classExprScriptName, programBase } from "../semantics/classes.js";
12
+ import { classExprCaptures, classExprScriptName, programBase, prototypeMethodList } from "../semantics/classes.js";
13
13
  export const classDeclMethods = {
14
14
  emitClassExprCode(cls) {
15
15
  if (classExprCaptures(cls, this.checker))
@@ -245,14 +245,9 @@ export const classDeclMethods = {
245
245
  if (this.library || !this.staticInits || !ts.isClassDeclaration(cls) || !this.facts.prototypeClasses().has(cls) || cls.typeParameters?.length)
246
246
  return;
247
247
  const owner = name.replace(/<.*$/, '');
248
- const seen = new Set();
249
- for (const m of cls.members) {
250
- if (!ts.isMethodDeclaration(m) || !m.body || isStatic(m) || ts.isPrivateIdentifier(m.name) || ts.isComputedPropertyName(m.name) || m.typeParameters?.length || m.asteriskToken || m.parameters.some((p) => p.dotDotDotToken || (ts.isIdentifier(p.name) && p.name.text === 'this')) || this.readsArguments(m))
251
- continue;
252
- const key = m.name.getText().replace(/^['"]|['"]$/g, '');
253
- if (seen.has(key))
254
- continue;
255
- seen.add(key);
248
+ for (const { method: m, key } of prototypeMethodList(cls, {
249
+ skip: (m, key) => m.parameters.some((p) => p.dotDotDotToken || (ts.isIdentifier(p.name) && p.name.text === 'this')) || this.readsArguments(m) || (k.plugin && !k.layout.inherited.has(key) && !(k.kitRoot && this.core?.kitMember(k.kitRoot, key)) && !this.facts.isNamed(key)),
250
+ })) {
256
251
  const args = m.parameters.map((p, idx) => this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${idx})`), this.paramType(p), true));
257
252
  const call = `__o.${this.methodIdent(key)}(${args.join(', ')})`;
258
253
  const body = this.returnTypeOf(m) === 'Unit' ? `${call}; null` : call;
@@ -142,7 +142,7 @@ export const classMethodsMethods = {
142
142
  const own = !overridden.has(n) && /^\$[be]\d+$/.test(n) ? 'internal ' : '';
143
143
  lines.push(' ' + this.func(m, this.methodIdent(n), (this.erasedSignatureMethods.has(m) ? `@JvmName("${n}__typed") ` : '') + own + (kotlinEquals ? 'override ' : this.memberMods(k, n))));
144
144
  // A plugin's objects are read untyped too (`handler.attachToView(view)` on an `any`): their methods by name.
145
- if (plugin && !m.parameters.some((p) => p.dotDotDotToken))
145
+ if (plugin && !m.typeParameters?.length && !m.parameters.some((p) => p.dotDotDotToken))
146
146
  k.dynMethods.push({ name: n, params: m.parameters.map((p) => this.paramType(p)), ret: this.returnTypeOf(m) });
147
147
  },
148
148
  abstractMethodCode(k, m) {
@@ -202,7 +202,7 @@ export const classMethodsMethods = {
202
202
  // Library mode: every method of the class is read by name as well (`font.getAndroidTypeface()` on an untyped font), overrides included.
203
203
  if (this.library || byName || droppedProtocolMembers.size > 0 || this.membersByName(cls) || this.states.downcastClass(cls) || this.states.byNameClass(cls)) {
204
204
  const addMethod = (m) => {
205
- if (!m.body || isStatic(m) || ts.isComputedPropertyName(m.name) || ts.isPrivateIdentifier(m.name) || m.parameters.some((p) => p.dotDotDotToken) || this.readsArguments(m))
205
+ if (!m.body || isStatic(m) || ts.isComputedPropertyName(m.name) || ts.isPrivateIdentifier(m.name) || m.typeParameters?.length || m.parameters.some((p) => p.dotDotDotToken) || this.readsArguments(m))
206
206
  return;
207
207
  const n = m.name.getText();
208
208
  if (dynMethods.some((d) => d.name === n && !d.key) || n === 'toString' || n === 'equals')
@@ -49,7 +49,7 @@ export class CoreKotlin extends KitTypes {
49
49
  this.t = t;
50
50
  }
51
51
  /** A kit property's value or method's result the kit holds nullable, read where core's typings say present. */
52
- kitNil(x) {
52
+ kotlinKitNil(x) {
53
53
  try {
54
54
  x = ts.skipOuterExpressions(x, ts.OuterExpressionKinds.Parentheses);
55
55
  const access = ts.isCallExpression(x) ? x.expression : x;
@@ -18,7 +18,7 @@ export const declarationsMethods = {
18
18
  if (!ts.isIdentifier(d.name) || !d.initializer)
19
19
  return false;
20
20
  const ownerFn = ts.findAncestor(d, (n) => ts.isFunctionLike(n) && 'body' in n && !!n.body);
21
- if (!ownerFn || !ownerFn.body || ts.isSourceFile(d.parent.parent.parent))
21
+ if (!ownerFn || !ownerFn.body || ts.isConstructorDeclaration(ownerFn) || ts.isSourceFile(d.parent.parent.parent))
22
22
  return false;
23
23
  const sym = this.checker.getSymbolAtLocation(d.name);
24
24
  if (!sym || (sym.declarations?.length ?? 0) !== 1)
@@ -3,7 +3,7 @@ import ts from 'typescript';
3
3
  import { nullishPart, nullishWrite } from "../semantics/placement.js";
4
4
  import { ident, isNullable, kotlinString, oneExpression, optionalType, RT } from "./syntax.js";
5
5
  import { reassignedBase } from "../semantics/ast.js";
6
- import { readWrite } from "../semantics/lang.js";
6
+ import { readWrite, unsafeReceiver } from "../semantics/lang.js";
7
7
  import { isKit, isUntyped, spelledType } from "../semantics/types.js";
8
8
  export const exprStatementsMethods = {
9
9
  assignIterated(target, item, part, _of) {
@@ -84,6 +84,18 @@ export const exprStatementsMethods = {
84
84
  return this.exprStatement(e.expression);
85
85
  if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.EqualsToken && !this.subst.has(e))
86
86
  return this.binary(e);
87
+ if (ts.isBinaryExpression(e) &&
88
+ e.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken &&
89
+ !this.subst.has(e) &&
90
+ ts.isElementAccessExpression(e.left) &&
91
+ !e.left.questionDotToken &&
92
+ !(e.left.flags & ts.NodeFlags.OptionalChain) &&
93
+ this.typeOf(e.left.expression) === 'JSArray<Double>' &&
94
+ !this.states.heldOptional(e.left.expression) &&
95
+ !unsafeReceiver(e.left.expression, this.checker) &&
96
+ !this.isAny(e.right)) {
97
+ return `${this.expr(e.left.expression)}.addDoubleAt(${this.toNumber(e.left.argumentExpression)}, ${this.toNumber(e.right)})`;
98
+ }
87
99
  const code = this.expr(e);
88
100
  // A value converted to nothing (`run { call(); Unit }`) where nothing reads it: what gives the value, alone.
89
101
  const m = ts.isCallExpression(e) ? this.marks.markOf(code) : undefined;
@@ -391,6 +391,7 @@ export const functionsMethods = {
391
391
  for (let k = given; k < slotParams.length; k++)
392
392
  params += `${params ? ', ' : ''}__u${k}: ${slotParams[k]}`;
393
393
  if (!ts.isMethodDeclaration(fn) && fn.name && fn.body && refersTo(fn.body, this.checker.getSymbolAtLocation(fn.name), this.checker)) {
394
+ this.refuseNamedGenerator(fn);
394
395
  const fnName = ident(fn.name.text);
395
396
  const pTypes = splitTopLevel(params)
396
397
  .map((p) => p.trim())
@@ -1,7 +1,7 @@
1
1
  // Literals as Kotlin: arrays, objects and class expressions, structural copies and dynamic objects.
2
2
  import ts from 'typescript';
3
3
  import { cast, destructuringSource, ident, isNullable, jsObjectCode, kotlinString, optionalType, splitTopLevel, spell, RT } from "./syntax.js";
4
- import { assertedOperand, evolvingElementContext, intersectionAliasMembers, isTypeParameterType, literalKey, openSpreadType, spreadOperand, unquoted, untypedVariableInitializer, wellKnownMember } from "../semantics/lang.js";
4
+ import { assertedOperand, evolvingElementContext, intersectionAliasMembers, isTypeParameterType, literalKey, openSpreadType, spreadOperand, unquoted, wellKnownMember } from "../semantics/lang.js";
5
5
  import { holdsNil, literalNotes, signatureField, shapePlanOfLiteral, spelledOptional, spreadElementNeedsMap, resultShapeNamed } from "../semantics/shapes.js";
6
6
  import { structural } from "../semantics/conversion.js";
7
7
  import { heldOf, isKit, isUntyped, parseNativeType, spelledType } from "../semantics/types.js";
@@ -84,7 +84,7 @@ export const literalsMethods = {
84
84
  }
85
85
  const el = t.replace(/^JSArray<(.*)>$/, '$1');
86
86
  if (!e.elements.length)
87
- return /^JSArray</.test(t) ? this.construction(`${t}()`, t) : `${t}()`;
87
+ return t === 'JSArray<Double>' ? this.construction('JSArray.doubles()', t) : /^JSArray</.test(t) ? this.construction(`${t}()`, t) : `${t}()`;
88
88
  // An array of objects holds a Kotlin null, which reads as undefined.
89
89
  const nulled = !isNullable(el) && e.elements.find((x) => !ts.isSpreadElement(x) && this.states.nullResult(ts.skipOuterExpressions(x, ts.OuterExpressionKinds.Parentheses)));
90
90
  if (nulled)
@@ -93,7 +93,8 @@ export const literalsMethods = {
93
93
  if (e.elements.some(ts.isOmittedExpression))
94
94
  throw this.error(e, 'an array hole', 'array-hole');
95
95
  const slot = this.elementSlot(e, el);
96
- return this.marks.marked(`${RT.jsArrayOf}<${el}>(${e.elements.map((x) => place(this.placement, x, slot(x))).join(', ')})`, { op: 'array', element: el });
96
+ const ctor = el === 'Double' ? 'JSArray.doublesOf' : `${RT.jsArrayOf}<${el}>`;
97
+ return this.marks.marked(`${ctor}(${e.elements.map((x) => place(this.placement, x, slot(x))).join(', ')})`, { op: 'array', element: el });
97
98
  }
98
99
  const parts = [];
99
100
  let run = [];
@@ -626,9 +627,4 @@ export const literalsMethods = {
626
627
  const value = made.arguments[0];
627
628
  return !!value && (value.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(value) && value.text === 'undefined'));
628
629
  },
629
- /** A variable declared without a type whose value is a read of a signal holding null (`const card = this.morning()`). */
630
- givenNullSignalValue(n) {
631
- const read = untypedVariableInitializer(n, (id) => this.resolve(id));
632
- return !!read && ts.isCallExpression(read) && !read.arguments.length && /^Signal<.*\?>$/.test(this.typeOf(read.expression));
633
- },
634
630
  };
@@ -3,7 +3,7 @@ import ts from 'typescript';
3
3
  import { KIT_NAMES_ANDROID } from "./library.js";
4
4
  import { ERRORS } from "../semantics/globals.js";
5
5
  import { IOS_TYPINGS, ident, isThisParameter, kotlinString, lambda, optionalType, RT } from "./syntax.js";
6
- import { accessedDeclaration, canReadArguments, isArguments, objectMethod } from "../semantics/lang.js";
6
+ import { accessedDeclaration, builtinConstructorSlot, canReadArguments, isArguments, objectMethod } from "../semantics/lang.js";
7
7
  import { hasModifier, isAppDeclarationFile, isLibDeclaration, isWriteTarget } from "../semantics/ast.js";
8
8
  import { isCoreDeclaration } from "../program/core-facts.js";
9
9
  import { isStatic } from "../semantics/throws.js";
@@ -20,9 +20,9 @@ export const namesMethods = {
20
20
  if (ERRORS[e.text])
21
21
  return `${ERRORS[e.text]}::class.java`;
22
22
  // Placed untyped or compared (`const f: any = Number`, `s.constructor === String`): singleton builtin constructor.
23
- const context = this.checker.getContextualType(e);
24
- if (!context || !this.checker.getNonNullableType(context).getCallSignatures()[0])
25
- return `js${e.text}Constructor`;
23
+ const { singleton } = builtinConstructorSlot(e, this.checker, (c) => isUntyped(spelledType(this.type(c, e))));
24
+ if (singleton)
25
+ return singleton;
26
26
  return `{ value: Any? -> ${e.text === 'Number' ? RT.jsToNumber : e.text === 'String' ? RT.jsToString : RT.jsTruthy}(value) }`;
27
27
  }
28
28
  // `Promise`, `Date`, `Array`, `Object` as values (`const { isArray } = Array`, a `PromiseConstructorLike` default): the runtime's.
@@ -37,7 +37,7 @@ export class AndroidNativeAPI {
37
37
  * Whether a typings declaration's Java binding holds null: a field's value, a method's result, a parameter's argument.
38
38
  * Java's reference types are platform types, null unless annotated `@NonNull`; its primitives never are.
39
39
  */
40
- holdsNil(d) {
40
+ jvmHoldsNil(d) {
41
41
  const param = ts.isParameter(d) ? d : null;
42
42
  const member = param ? param.parent : d;
43
43
  const k = param ? member.parameters.indexOf(param) : -1;
@@ -12,7 +12,8 @@ import { isLibDeclaration } from "../semantics/ast.js";
12
12
  import { nullAs } from "./expressions.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 { flattenStringConcat, planRelational } from "../semantics/lower.js";
15
+ import { flattenStringConcat, planArithmetic, planEquality, planLogicalAssign, planRelational } from "../semantics/lower.js";
16
+ import { isReadonlySignalProperty } from "../semantics/signals.js";
16
17
  /** BigInt's operations the backend spells as an operator. */
17
18
  const BIGINT_INFIX = { add: '+', subtract: '-', multiply: '*', and: 'and', or: 'or', xor: 'xor' };
18
19
  export const operatorsMethods = {
@@ -105,31 +106,30 @@ export const operatorsMethods = {
105
106
  case K.AsteriskAsteriskEqualsToken:
106
107
  return `${target()} = ${RT.jsPow}(${this.heldOptionalNumber(e.left) ? this.undefinedAs(this.expr(e.left), 'Double') : this.isAny(e.left) ? this.toNumber(e.left) : l()}, ${this.toNumber(e.right)})`;
107
108
  case K.QuestionQuestionEqualsToken:
108
- return `if (${RT.jsIsNullish}(${l()})) ${this.assignment(e.left, e.right)}`;
109
109
  case K.BarBarEqualsToken:
110
- return `if (!${RT.jsTruthy}(${l()})) ${this.assignment(e.left, e.right)}`;
111
- case K.AmpersandAmpersandEqualsToken:
112
- return `if (${RT.jsTruthy}(${l()})) ${this.assignment(e.left, e.right)}`;
113
- case K.PlusToken: {
114
- if (this.isString(e.left) || this.isString(e.right))
110
+ case K.AmpersandAmpersandEqualsToken: {
111
+ const plan = planLogicalAssign(op);
112
+ const guard = plan.op === '??=' ? `${RT.jsIsNullish}(${l()})` : plan.op === '||=' ? `!${RT.jsTruthy}(${l()})` : `${RT.jsTruthy}(${l()})`;
113
+ return `if (${guard}) ${this.assignment(e.left, e.right)}`;
114
+ }
115
+ case K.PlusToken:
116
+ case K.MinusToken:
117
+ case K.AsteriskToken:
118
+ case K.SlashToken:
119
+ case K.PercentToken:
120
+ case K.AsteriskAsteriskToken: {
121
+ const plan = planArithmetic(op, this.isString(e.left), this.isString(e.right), this.isAny(e.left), this.isAny(e.right));
122
+ if (plan.kind === 'concat')
115
123
  return `${concatOperand(this, e.left, untyped)} + ${concatOperand(this, e.right, untyped)}`;
116
- if (this.isAny(e.left) || this.isAny(e.right)) {
124
+ if (plan.kind === 'dynamicAdd') {
117
125
  const sum = addCall(this, e, untyped), t = this.typeOf(e);
118
126
  // An operand held untyped though TypeScript types it, and so the sum, a number or string.
119
127
  return isUntyped(spelledType(t)) ? sum : this.fromAnyCode(sum, t);
120
128
  }
121
- return `${this.toNumber(e.left)} + ${this.toNumber(e.right)}`;
129
+ if (plan.op === '**')
130
+ return `${RT.jsPow}(${this.toNumber(e.left)}, ${this.toNumber(e.right)})`;
131
+ return `${this.toNumber(e.left)} ${plan.op} ${this.toNumber(e.right)}`;
122
132
  }
123
- case K.MinusToken:
124
- return `${this.toNumber(e.left)} - ${this.toNumber(e.right)}`;
125
- case K.AsteriskToken:
126
- return `${this.toNumber(e.left)} * ${this.toNumber(e.right)}`;
127
- case K.SlashToken:
128
- return `${this.toNumber(e.left)} / ${this.toNumber(e.right)}`;
129
- case K.PercentToken:
130
- return `${this.toNumber(e.left)} % ${this.toNumber(e.right)}`;
131
- case K.AsteriskAsteriskToken:
132
- return `${RT.jsPow}(${this.toNumber(e.left)}, ${this.toNumber(e.right)})`;
133
133
  case K.EqualsEqualsEqualsToken:
134
134
  case K.ExclamationEqualsEqualsToken:
135
135
  case K.EqualsEqualsToken:
@@ -338,9 +338,9 @@ export const operatorsMethods = {
338
338
  },
339
339
  equality(e) {
340
340
  const K = ts.SyntaxKind;
341
- const op = e.operatorToken.kind;
342
- const negate = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
343
- const strict = op === K.EqualsEqualsEqualsToken || op === K.ExclamationEqualsEqualsToken;
341
+ const eq = planEquality(e.operatorToken.kind, false, false, false, false);
342
+ const negate = eq.negated;
343
+ const strict = eq.kind === 'strict';
344
344
  const isNullish = (x) => x.kind === K.NullKeyword || (ts.isIdentifier(x) && x.text === 'undefined');
345
345
  const [a, b] = [e.left, e.right];
346
346
  const lt = this.typeOf(a);
@@ -420,7 +420,7 @@ export const operatorsMethods = {
420
420
  }
421
421
  },
422
422
  /** Whether a `Signal<T>` node is lowered as a Kotlin property reading its value (`val x: T get() = …`) rather than a `Signal<T>`. */
423
- isComputedProperty(n) {
423
+ isKotlinComputedProperty(n) {
424
424
  if (this.library)
425
425
  return false;
426
426
  const decl = ts.isIdentifier(n) || ts.isPropertyAccessExpression(n) || ts.isPrivateIdentifier(n) ? this.resolve(n)?.valueDeclaration : n;
@@ -431,13 +431,13 @@ export const operatorsMethods = {
431
431
  if (!ts.isPropertyDeclaration(decl) || !ts.isClassLike(decl.parent) || !decl.initializer)
432
432
  return false;
433
433
  const init = decl.initializer, callee = this.calleeName(init);
434
- if (this.framework.heldSignal(callee) || /\.asReadonly$/.test(callee))
434
+ if (this.framework.heldSignal(callee) || isReadonlySignalProperty(decl, this.checker, this.framework, callee))
435
435
  return true;
436
436
  return this.signalAlias(decl);
437
437
  },
438
438
  /** A read-only signal's current value. */
439
439
  signalValue(e) {
440
- return this.isComputedProperty(e) ? this.expr(e) : `${this.expr(e)}.value`;
440
+ return this.isKotlinComputedProperty(e) ? this.expr(e) : `${this.expr(e)}.value`;
441
441
  },
442
442
  /** A field initialized with another read-only signal (`dayColor = ink`, a module's memo): a property reading through it. */
443
443
  signalAlias(m) {
@@ -23,7 +23,7 @@ export const optionalChainsMethods = {
23
23
  return `(${this.coerce(e.left, optionalType(this.typeOf(e)))} ?: ${rightMaybe})`;
24
24
  }
25
25
  // A kit method whose Kotlin signature returns nullable (`ViewBase.getViewById`: `ViewBase?`) though core's typings say present.
26
- if (ts.isCallExpression(e) && !this.library && !this.nullOk.has(e) && !isNullable(this.typeOf(e)) && this.isObjectRef(e) && !isFunctionType(this.typeOf(e)) && this.core?.kitNil?.(e)) {
26
+ if (ts.isCallExpression(e) && !this.library && !this.nullOk.has(e) && !isNullable(this.typeOf(e)) && this.isObjectRef(e) && !isFunctionType(this.typeOf(e)) && this.core?.kotlinKitNil?.(e)) {
27
27
  this.nullOk.add(e);
28
28
  try {
29
29
  return this.expr(e);
@@ -590,7 +590,7 @@ export const overridesMethods = {
590
590
  * App mode: a type name Kotlin code already has unqualified (a default import's, the runtime's, a thread annotation's,
591
591
  * whose import outranks the app's package). Java classes are spelled qualified, so their names hide nothing.
592
592
  */
593
- nativeClash(name) {
593
+ kotlinTypeClash(name) {
594
594
  return !this.library && (KOTLIN_NATIVE_TYPES.has(name) || runtimeTypeName(name) || THREAD_ANNOTATIONS.includes(name));
595
595
  },
596
596
  /**
@@ -692,7 +692,7 @@ export const overridesMethods = {
692
692
  const kitClash = (list.some((x) => typeLike(x.decl)) && !!this.core?.has(name) && !this.core.nested?.(name)) || (coreFunctions.has(name) && list.some((x) => ts.isFunctionDeclaration(x.decl) || ts.isVariableDeclaration(x.decl)));
693
693
  // A type the hand-written kit declares for itself, or an app's type named as one Kotlin has already (`Pair`): the
694
694
  // generated one takes its module's name.
695
- const internalClash = !!this.library?.internalTypes?.has(name) || (list.some((x) => typeLike(x.decl) || ts.isInterfaceDeclaration(x.decl)) && this.nativeClash(name));
695
+ const internalClash = !!this.library?.internalTypes?.has(name) || (list.some((x) => typeLike(x.decl) || ts.isInterfaceDeclaration(x.decl)) && this.kotlinTypeClash(name));
696
696
  if (list.length < 2 && !kitClash && !internalClash)
697
697
  continue;
698
698
  // The app's declaration keeps its name (the first app module's, of several); the others take their module's.
@@ -43,7 +43,7 @@ export const stateBackendMethods = {
43
43
  return t.library;
44
44
  },
45
45
  get native() {
46
- return t.native;
46
+ return t.native ? { holdsNil: (d) => !!t.native.jvmHoldsNil?.(d) } : null;
47
47
  },
48
48
  get framework() {
49
49
  return t.framework;
@@ -67,7 +67,11 @@ export const stateBackendMethods = {
67
67
  const t = this.heldSpelling(x);
68
68
  return heldAs(t, isNullable(t));
69
69
  },
70
- kitNil: (x) => !this.library && !!this.core?.kitNil?.(x),
70
+ kitNil: (x) => !this.library && !!this.core?.kotlinKitNil?.(x),
71
+ untypedCastChecks: (_e, t) => {
72
+ const type = spell(t);
73
+ return this.isObjectType(type) && !/^JS(Array|Record|Promise|Date|Error)\b/.test(type);
74
+ },
71
75
  declaredOptional: (x) => {
72
76
  const sym = this.resolve(x);
73
77
  return !!sym && (!!this.undefinedVars.get(sym)?.endsWith('?') || !!this.declaredTypeOf(x)?.endsWith('?'));
@@ -503,7 +503,7 @@ export class Translator {
503
503
  if (sub)
504
504
  return this.convert(sub.code, this.typeOf(sub.bare), target);
505
505
  const inner = /^Signal<(.*)>\??$/.exec(target)?.[1];
506
- return inner && this.isComputedProperty(e) ? `Signal.computing { ${this.coerce(e, inner)} }` : null;
506
+ return inner && this.isKotlinComputedProperty(e) ? `Signal.computing { ${this.coerce(e, inner)} }` : null;
507
507
  },
508
508
  readHeld: (e) => this.readHeld(e),
509
509
  untypedRead: (code, target) => this.fromAnyCode(code, target, this.lenient),
@@ -4,7 +4,7 @@ import { KIT_NAMES_ANDROID } from "./library.js";
4
4
  import { BUFFER_TYPES, WEB_DICTIONARIES, webClassName } from "../semantics/globals.js";
5
5
  import { SPELLING, spell, destructuringSource, functionTypeParts, kotlinString, nullishType, optionalElementsType, optionalType, presentConst, RT } from "./syntax.js";
6
6
  import { ambientBase, evolvingArrayRead, evolvingArrayType, isAmbientClass, isRegExpProtocol, memberOwner, namesOwnTypeParameter, tokenClassBase, isArguments } from "../semantics/lang.js";
7
- import { nullishSignalType } from "../semantics/signals.js";
7
+ import { isGivenNullSignalValue, nullishSignalType } from "../semantics/signals.js";
8
8
  import { hasModifier, isLibDeclaration, isWriteTarget, implementationOf, takesOwnThis } from "../semantics/ast.js";
9
9
  import { isCoreDeclaration } from "../program/core-facts.js";
10
10
  import { coreTypeKind, eventDataTypeLiteral, hasMappedIntersection, isJsDocConstructorFunction, isKit, isLibObjectType, isNamed, isUntyped, libraryNativeType, libraryType, mappedOrErasedType, nonNullableInner, nonOptionalSpelling, parseNativeType, spelledType, valueModuleKind } from "../semantics/types.js";
@@ -194,7 +194,7 @@ export const typesMethods = {
194
194
  if (javaClass)
195
195
  return javaClass;
196
196
  // A program type renamed for a name Kotlin has already (`Iterator`, `Pair`) is not the library's type of that name.
197
- const clashing = !this.library && sym?.valueDeclaration && this.nativeClash(sym.name) ? this.topNames().get(sym.valueDeclaration) : undefined;
197
+ const clashing = !this.library && sym?.valueDeclaration && this.kotlinTypeClash(sym.name) ? this.topNames().get(sym.valueDeclaration) : undefined;
198
198
  if (clashing)
199
199
  return `${clashing}${this.declaredTypeArguments(t, sym.valueDeclaration, where)}`;
200
200
  const kind = name === undefined ? undefined : this.framework.signalKind(name);
@@ -204,7 +204,7 @@ export const typesMethods = {
204
204
  return `Signal<${arg(0)}>`;
205
205
  }
206
206
  if (kind === 'computed')
207
- return where && this.isComputedProperty(where) ? arg(0) : `Signal<${arg(0)}>`;
207
+ return where && this.isKotlinComputedProperty(where) ? arg(0) : `Signal<${arg(0)}>`;
208
208
  if (kind)
209
209
  return `Signal<${arg(0)}>`;
210
210
  const mapped = name === undefined ? undefined : this.framework.typeMapping(name);
@@ -506,7 +506,7 @@ export const typesMethods = {
506
506
  const t = this.isLenientDecl(own) ? this.lenientRef(declared) : this.states.looseDeclaration(own) ? optionalType(declared) : declared;
507
507
  if (this.holdingNull(t, n))
508
508
  return t.replace(/>$/, '?>');
509
- if (['String', 'Double', 'Boolean'].includes(t) && this.givenNullSignalValue(n))
509
+ if (['String', 'Double', 'Boolean'].includes(t) && isGivenNullSignalValue(n, (id) => this.resolve(id), (read) => ts.isCallExpression(read) && !read.arguments.length && /^Signal<.*\?>$/.test(this.typeOf(read.expression))))
510
510
  return `${t}?`;
511
511
  if (/^JSArray<String>\??$/.test(t) && this.unsetGroups(n))
512
512
  return t.replace('JSArray<String>', 'JSArray<String?>');