@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
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`
@@ -86,6 +86,15 @@ export class KitTypes {
86
86
  isKitView(name) {
87
87
  return kitExtends(this.index, name, 'View');
88
88
  }
89
+ /** Whether the kit applies `name` by name on this view class (a property in its setProperty). */
90
+ isViewProperty(owner, name) {
91
+ if (owner === 'Style')
92
+ return [...this.index.values()].some((t) => kitExtends(this.index, t.name, 'View') && t.props.has(name));
93
+ for (let t = this.index.get(owner); t; t = t.base ? this.index.get(t.base.replace(/\(.*$/, '')) : undefined)
94
+ if (t.props.has(name))
95
+ return true;
96
+ return false;
97
+ }
89
98
  /** A view, or a view's `style`: properties by name. */
90
99
  isView(owner) {
91
100
  return owner === 'Style' || kitExtends(this.index, owner, 'View');
@@ -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 { observerSlot, place, 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";
@@ -247,6 +247,8 @@ export const accessMethods = {
247
247
  return ((base.endsWith('?') || held) && !proven && !e.questionDotToken && !inChain && !isSelf(target, this.subst)) || this.isAsserted(code) ? this.present(code, name, target, isWriteTarget(e)) : code;
248
248
  };
249
249
  if (name === 'length' && this.isString(target)) {
250
+ if (!e.questionDotToken && !inChain && ts.isIdentifier(target) && this.stringBuilders.has(this.resolve(target)))
251
+ return `${ident(target.text)}.length.toDouble()`;
250
252
  return e.questionDotToken || inChain ? `${this.expr(target)}?.length?.toDouble()` : `${recv()}.length.toDouble()`;
251
253
  }
252
254
  if (name === 'length' && (base.startsWith('Pair<') || base.startsWith('Triple<')))
@@ -321,7 +323,7 @@ export const accessMethods = {
321
323
  const describedClass = this.library && symbol?.valueDeclaration?.getSourceFile().isDeclarationFile && !isLibDeclaration(symbol.valueDeclaration) && !this.native?.isNativeDeclaration(symbol.valueDeclaration) ? this.compiledClasses().get(this.checker.getNonNullableType(this.checker.getTypeAtLocation(target)).getSymbol()?.name ?? '') : undefined;
322
324
  // Library mode: a member TypeScript does not find on the type (lenient code reading what the type omits): read by name.
323
325
  const unknown = this.library && !symbol && !e.name.text.startsWith('#') && this.isObjectRef(target);
324
- if (((describedClass && !this.compiledMember(describedClass, name)) || unknown) && !(ts.isCallExpression(e.parent) && e.parent.expression === e && !e.parent.questionDotToken)) {
326
+ if (((describedClass && !this.declaresCompiledMember(describedClass, name)) || unknown) && !(ts.isCallExpression(e.parent) && e.parent.expression === e && !e.parent.questionDotToken)) {
325
327
  const t = this.typeOf(e);
326
328
  const code = `${e.questionDotToken || inChain ? RT.jsGetIfPresent : RT.jsGet}(${this.expr(target)}, ${kotlinString(name)})`;
327
329
  // Called (`x.callback?.(…)`): the function as script holds it, which the call reads.
@@ -350,7 +352,7 @@ export const accessMethods = {
350
352
  const plain = `${receiver}${dot}${ident(name)}`;
351
353
  const read = dot === '.' ? this.marks.marked(plain, { op: 'member', of: this.marks.valueOf(receiver), name }) : plain;
352
354
  // A non-strict app's optional member is held optional though its type says present: a value read reads its undefined.
353
- if ((this.optionalMember(e) || (!e.questionDotToken && !(e.flags & ts.NodeFlags.OptionalChain) && !!symbol && this.states.shapeFieldOptional(symbol))) && !isWriteTarget(e) && !this.nullOk.has(e) && ['String', 'Double', 'Boolean'].includes(this.typeOf(e)))
355
+ if ((this.isLenientOptionalMember(e) || (!e.questionDotToken && !(e.flags & ts.NodeFlags.OptionalChain) && !!symbol && this.states.shapeFieldOptional(symbol))) && !isWriteTarget(e) && !this.nullOk.has(e) && ['String', 'Double', 'Boolean'].includes(this.typeOf(e)))
354
356
  return this.undefinedAs(read, this.typeOf(e));
355
357
  return this.narrowed(e, read);
356
358
  },
@@ -425,7 +427,7 @@ export const accessMethods = {
425
427
  if (ts.isPropertyAccessExpression(x) && this.library && this.resolve(x.name)?.declarations?.some((d) => ts.isPropertySignature(d) && !isLibDeclaration(d)))
426
428
  return null;
427
429
  if (ts.isPropertyAccessExpression(x)) {
428
- if (!(this.optionalMember(x) || (!this.typeOf(x).endsWith('?') && !!this.declaredTypeOf(x)?.endsWith('?'))))
430
+ if (!(this.isLenientOptionalMember(x) || (!this.typeOf(x).endsWith('?') && !!this.declaredTypeOf(x)?.endsWith('?'))))
429
431
  return null;
430
432
  return this.isExpando(x) ? this.fromAny(`${RT.jsGet}(${this.expr(x.expression)}, ${kotlinString(x.name.text)})`, optionalType(this.typeOf(x))) : `${this.expr(x.expression)}.${ident(x.name.text)}`;
431
433
  }
@@ -464,7 +466,7 @@ export const accessMethods = {
464
466
  return ['String', 'Double', 'Boolean'].includes(t) ? this.fromAny(`${RT.jsGet}(${this.expr(x.expression)}, ${kotlinString(x.name.text)})`, optionalType(t)) : null;
465
467
  },
466
468
  /** A non-strict app's read of an object type's optional member (`o.a`, `a?: string`), which Kotlin holds optional. */
467
- optionalMember(x) {
469
+ isLenientOptionalMember(x) {
468
470
  if (!this.lenientApp || this.library || x.questionDotToken || x.flags & ts.NodeFlags.OptionalChain || this.typeOf(x).endsWith('?'))
469
471
  return false;
470
472
  const d = this.resolve(x.name)?.valueDeclaration;
@@ -526,6 +528,12 @@ export const accessMethods = {
526
528
  const rt = this.typeOf(e);
527
529
  if (t === 'JSArray<Any?>' && !isUntyped(spelledType(rt)))
528
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
+ }
529
537
  return this.undefinedAs(this.maybeUndefined(e), rt);
530
538
  }
531
539
  if (t === 'JSMatch') {
@@ -593,11 +601,6 @@ export const accessMethods = {
593
601
  }
594
602
  throw this.error(e, 'indexing this type', 'index-type');
595
603
  },
596
- /** `assertedUntyped`'s cast: to an object type other than the kit's own containers, promises, dates and errors. */
597
- untypedCastChecks(_e, t) {
598
- const type = spell(t);
599
- return this.isObjectType(type) && !/^JS(Array|Record|Promise|Date|Error)\b/.test(type);
600
- },
601
604
  /** An `assertedUntyped` assertion read as the nullable it may be: null where the value is undefined or null. */
602
605
  /** `x as Iterable<T>` of a value not held as one: whatever x holds iterated, as GetIterator does where it is iterated. */
603
606
  iterableCast(e) {
@@ -630,10 +633,6 @@ export const accessMethods = {
630
633
  const holder = ts.findAncestor(e.parent, (p) => !ts.isParenthesizedExpression(p));
631
634
  return holder && ts.isVariableDeclaration(holder) ? this.widerAsserted(holder) : null;
632
635
  },
633
- /** `x` read by an equality or `typeof` (`ObserverSlot`). */
634
- observe(x, read = 'untyped') {
635
- return place(this.placement, x, observerSlot(this.placement, read));
636
- },
637
636
  /**
638
637
  * A read `observedAsIs` (an identity operand, `instanceof`'s left): the nullable it may be, never asserted present.
639
638
  * Library mode reads an untyped value as it is held: `maybeUndefined` would cast it to the declared type.
@@ -91,7 +91,7 @@ export const argumentsMethods = {
91
91
  return (isUntyped(spelledType(pt)) && this.untypedArrow(a)) || null;
92
92
  },
93
93
  /** A function held in a variable, parameter or field (an overloaded method's implementation bound): a Kotlin function type, which has no defaults. */
94
- heldFunction(callee) {
94
+ isHeldFunctionValue(callee) {
95
95
  const name = ts.isPropertyAccessExpression(callee) ? callee.name : ts.isIdentifier(callee) ? callee : null;
96
96
  const d = name && this.checker.getSymbolAtLocation(name)?.valueDeclaration;
97
97
  return !!d && !d.getSourceFile().isDeclarationFile && (ts.isVariableDeclaration(d) || ts.isParameter(d) || ts.isPropertyDeclaration(d));
@@ -157,7 +157,7 @@ export const argumentsMethods = {
157
157
  out.push(`${this.restType(params[restAt])}()`);
158
158
  const decl = sig?.getDeclaration();
159
159
  // A function value takes every parameter; a plugin's call (its code unchecked) may leave out one the callee requires.
160
- const missing = count !== undefined || restAt >= 0 || !decl || ts.isJSDocSignature(decl) ? undefined : ts.isFunctionTypeNode(decl) || ts.isCallSignatureDeclaration(decl) || ts.isArrowFunction(decl) || ts.isFunctionExpression(decl) || (ts.isCallExpression(e) && this.heldFunction(e.expression)) ? 'empty' : !this.library && this.inPluginFile(e) ? 'undefined' : undefined;
160
+ const missing = count !== undefined || restAt >= 0 || !decl || ts.isJSDocSignature(decl) ? undefined : ts.isFunctionTypeNode(decl) || ts.isCallSignatureDeclaration(decl) || ts.isArrowFunction(decl) || ts.isFunctionExpression(decl) || (ts.isCallExpression(e) && this.isHeldFunctionValue(e.expression)) ? 'empty' : !this.library && this.inPluginFile(e) ? 'undefined' : undefined;
161
161
  for (let k = covered; missing && k < params.length; k++) {
162
162
  const s = this.missingSlot(e, params[k], k, missing);
163
163
  if (!s)
@@ -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))
@@ -68,6 +68,7 @@ export const classDeclMethods = {
68
68
  this.cssTypeMemberCode(k);
69
69
  this.classDecoratorsCode(k);
70
70
  this.staticsByNameCode(k);
71
+ this.prototypeMethodsCode(k);
71
72
  this.computedMethodsCode(k);
72
73
  this.methodMembersCode(k);
73
74
  this.ownPropertiesCode(k);
@@ -239,6 +240,20 @@ export const classDeclMethods = {
239
240
  this.staticInits.push(` JSPrototypes.declareStatics(${owner}::class.java, listOf(${entries.join(', ')}))`);
240
241
  }
241
242
  },
243
+ prototypeMethodsCode(k) {
244
+ const { cls, name } = k;
245
+ if (this.library || !this.staticInits || !ts.isClassDeclaration(cls) || !this.facts.prototypeClasses().has(cls) || cls.typeParameters?.length)
246
+ return;
247
+ const owner = name.replace(/<.*$/, '');
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
+ })) {
251
+ const args = m.parameters.map((p, idx) => this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${idx})`), this.paramType(p), true));
252
+ const call = `__o.${this.methodIdent(key)}(${args.join(', ')})`;
253
+ const body = this.returnTypeOf(m) === 'Unit' ? `${call}; null` : call;
254
+ this.staticInits.push(` JSPrototypes.of(${owner}::class.java).defineProperty(${kotlinString(key)}, JSPropertyDescriptor(value = JSMethod(${m.parameters.length}) { __this, __a -> val __o = ${RT.jsBox}(__this) as? ${owner} ?: throw JSException(JSTypeError("Illegal invocation")); ${body} }, hasValue = true, enumerable = false, writable = true, configurable = true))`);
255
+ }
256
+ },
242
257
  ownPropertiesCode(k) {
243
258
  if (k.isView && !this.generatedKit) {
244
259
  const own = k.fields.filter(isPropertyField).map((f) => f.name);
@@ -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')
@@ -229,10 +229,7 @@ export const componentMethods = {
229
229
  statics.push(...(this.framework.hooks.componentStatics?.(this, cls) ?? []));
230
230
  return { params, lines, statics };
231
231
  },
232
- /** A component created as a root view (bootstrap, route, dialog): made and rendered as the framework makes it. */
233
- rootView(cls, type, make) {
234
- return this.framework.hooks.wrapRootView ? this.framework.hooks.wrapRootView(this, cls, type, make) : make;
235
- },
232
+ /* rootView is installed from semantics/lowering-methods.ts */
236
233
  /**
237
234
  * `Object.defineProperty` on an app class's instance that makes one of its declared fields an accessor, read-only,
238
235
  * hidden or fixed: the class's Kotlin field keeps none of these.
@@ -260,9 +257,7 @@ export const componentMethods = {
260
257
  const iface = m.parent;
261
258
  return ts.isInterfaceDeclaration(iface) && !!iface.typeParameters?.length && !iface.getSourceFile().isDeclarationFile && this.protocols.has(this.topName(iface, iface.name.text));
262
259
  },
263
- calleeName(e) {
264
- return ts.isCallExpression(e) ? e.expression.getText() : '';
265
- },
260
+ /* calleeName is installed from semantics/lowering-methods.ts */
266
261
  /** The names an app class's members override: its app base classes' and its interfaces'. */
267
262
  overridden(cls, implemented) {
268
263
  const out = new Set();
@@ -1,7 +1,7 @@
1
1
  import ts from 'typescript';
2
2
  import { heldLoss } from "../semantics/losses.js";
3
3
  import { join } from 'node:path';
4
- import { addedDeclarations, augmentedProperty, isCoreDeclaration, ownPropertyOnly } from "../program/core-facts.js";
4
+ import { addedDeclarations, augmentedProperty, inheritedCoreOwner, isCoreDeclaration, ownPropertyOnly } from "../program/core-facts.js";
5
5
  import { KitTypes, coreClass, kitExtends, kitMember } from "../kit/kit-index.js";
6
6
  import { KIT_NAMES_ANDROID } from "./library.js";
7
7
  import { functionTypeParts, kotlinString, numberLiteral, safeCast, splitTopLevel, RT } from "./syntax.js";
@@ -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;
@@ -248,7 +248,7 @@ export class CoreKotlin extends KitTypes {
248
248
  * (`Utils.android` of utils/index is utils/native-helper's): that module's object.
249
249
  */
250
250
  ownerOf(target, name) {
251
- let owner = isMixinOwnMember(name, this.t.checker, (s) => this.t.mixinOf(s)) ? null : (this.owner(target) ?? this.inheritedOwner(target, name));
251
+ let owner = isMixinOwnMember(name, this.t.checker, (s) => this.t.mixinOf(s)) ? null : (this.owner(target) ?? inheritedCoreOwner(target, name, this.t.checker, (c) => this.t.kitRootOf(c)));
252
252
  if (owner && !kitMember(this.index, owner.name, name.text))
253
253
  owner = this.renamedOwner(owner, name.text) ?? owner;
254
254
  if (!owner || !owner.isStatic || !owner.name.startsWith('Core_') || kitMember(this.index, owner.name, name.text))
@@ -267,16 +267,6 @@ export class CoreKotlin extends KitTypes {
267
267
  const module = decl && isCoreDeclaration(decl) ? this.moduleObject(decl) : null;
268
268
  return module && kitMember(this.index, module, name.text) ? { name: module, isStatic: true } : owner;
269
269
  }
270
- /** A core member read through a class of the app or a plugin that extends a core class (`this.isPassThroughParentEnabled` in a GridLayout subclass). */
271
- inheritedOwner(target, name) {
272
- const c = this.t.checker;
273
- const decl = c.getSymbolAtLocation(name)?.valueDeclaration;
274
- if (!decl || !isCoreDeclaration(decl))
275
- return null;
276
- const cls = c.getNonNullableType(c.getTypeAtLocation(target)).getSymbol()?.valueDeclaration;
277
- const root = cls && ts.isClassLike(cls) && !cls.getSourceFile().isDeclarationFile ? this.t.kitRootOf(cls) : null;
278
- return root ? { name: root, isStatic: false } : null;
279
- }
280
270
  /**
281
271
  * `on`/`off`/`once` with a named function: a function value made once per
282
272
  * evaluation has no identity across them, so the kit matches a listener by
@@ -312,15 +302,6 @@ export class CoreKotlin extends KitTypes {
312
302
  throw this.t.error(e, `${owner}.${name} (kit-android has no such member)`);
313
303
  return m;
314
304
  }
315
- isViewProperty(owner, name) {
316
- // A style property applies to any view; the kit's classes each apply their own.
317
- if (owner === 'Style')
318
- return [...this.index.values()].some((t) => kitExtends(this.index, t.name, 'View') && t.props.has(name));
319
- for (let t = this.index.get(owner); t; t = t.base ? this.index.get(t.base.replace(/\(.*$/, '')) : undefined)
320
- if (t.props.has(name))
321
- return true;
322
- return false;
323
- }
324
305
  /** `object.name` of an `augmentedProperty` on a core-typed object, outside a chain: the read of its own property (`Any?`), or null. */
325
306
  augmentedRead(e) {
326
307
  if (ts.isOptionalChain(e) || this.constant(e) !== null)
@@ -10,6 +10,86 @@ import { programBase } from "../semantics/classes.js";
10
10
  import { definedField } from "../semantics/shapes.js";
11
11
  import { isKit, isNamed, isUntyped, spelledType } from "../semantics/types.js";
12
12
  export const declarationsMethods = {
13
+ /**
14
+ * Whether a function-local `let s = ...` of type `String` is only ever mutated via statement-level `s += ...`
15
+ * (at least once inside a loop) and never captured by a closure: safe to back with a `StringBuilder` to avoid O(N^2) copies.
16
+ */
17
+ isStringBuilderLocal(d) {
18
+ if (!ts.isIdentifier(d.name) || !d.initializer)
19
+ return false;
20
+ const ownerFn = ts.findAncestor(d, (n) => ts.isFunctionLike(n) && 'body' in n && !!n.body);
21
+ if (!ownerFn || !ownerFn.body || ts.isConstructorDeclaration(ownerFn) || ts.isSourceFile(d.parent.parent.parent))
22
+ return false;
23
+ const sym = this.checker.getSymbolAtLocation(d.name);
24
+ if (!sym || (sym.declarations?.length ?? 0) !== 1)
25
+ return false;
26
+ let appendedInLoop = false;
27
+ let disqualified = false;
28
+ const visit = (n, inNestedFn, inLoop) => {
29
+ if (disqualified)
30
+ return;
31
+ if (n !== ownerFn && (ts.isFunctionLike(n) || ts.isClassLike(n))) {
32
+ ts.forEachChild(n, (c) => visit(c, true, inLoop));
33
+ return;
34
+ }
35
+ if (ts.isIdentifier(n) && n !== d.name) {
36
+ const p = n.parent;
37
+ if ((ts.isPropertyAccessExpression(p) && p.name === n) || ((ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p) || ts.isPropertyDeclaration(p)) && p.name === n))
38
+ return;
39
+ if (this.checker.getSymbolAtLocation(n) === sym) {
40
+ if (inNestedFn || (ts.isShorthandPropertyAssignment(p) && p.name === n)) {
41
+ disqualified = true;
42
+ return;
43
+ }
44
+ if (ts.isBinaryExpression(p) && p.left === n && p.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && p.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
45
+ if (p.operatorToken.kind !== ts.SyntaxKind.PlusEqualsToken || !ts.isExpressionStatement(p.parent)) {
46
+ disqualified = true;
47
+ return;
48
+ }
49
+ // Reject `s += ...s...` self-append edge case.
50
+ let readsSelf = false;
51
+ const checkRhs = (x) => {
52
+ if (ts.isIdentifier(x) && this.checker.getSymbolAtLocation(x) === sym)
53
+ readsSelf = true;
54
+ if (!readsSelf)
55
+ ts.forEachChild(x, checkRhs);
56
+ };
57
+ checkRhs(p.right);
58
+ if (readsSelf) {
59
+ disqualified = true;
60
+ return;
61
+ }
62
+ if (inLoop)
63
+ appendedInLoop = true;
64
+ return;
65
+ }
66
+ if (ts.isPrefixUnaryExpression(p) || ts.isPostfixUnaryExpression(p)) {
67
+ if (p.operator === ts.SyntaxKind.PlusPlusToken || p.operator === ts.SyntaxKind.MinusMinusToken) {
68
+ disqualified = true;
69
+ return;
70
+ }
71
+ }
72
+ if ((ts.isForInStatement(p) || ts.isForOfStatement(p)) && p.initializer === n) {
73
+ disqualified = true;
74
+ return;
75
+ }
76
+ if (ts.isArrayLiteralExpression(p) || ts.isObjectLiteralExpression(p) || ts.isSpreadAssignment(p) || ts.isSpreadElement(p)) {
77
+ let up = p;
78
+ while (ts.isArrayLiteralExpression(up) || ts.isObjectLiteralExpression(up) || ts.isPropertyAssignment(up) || ts.isSpreadAssignment(up) || ts.isSpreadElement(up))
79
+ up = up.parent;
80
+ if (ts.isBinaryExpression(up) && up.operatorToken.kind === ts.SyntaxKind.EqualsToken && up.left.pos <= n.pos && n.end <= up.left.end) {
81
+ disqualified = true;
82
+ return;
83
+ }
84
+ }
85
+ }
86
+ }
87
+ const nextLoop = inLoop || ts.isIterationStatement(n, false);
88
+ ts.forEachChild(n, (c) => visit(c, inNestedFn, nextLoop));
89
+ };
90
+ visit(ownerFn.body, false, false);
91
+ return appendedInLoop && !disqualified;
92
+ },
13
93
  declarationList(list, lowered) {
14
94
  const constant = !!(list.flags & ts.NodeFlags.Const);
15
95
  // A `let` or `var` set once, where it is declared, is a constant too.
@@ -21,11 +101,6 @@ export const declarationsMethods = {
21
101
  !assignsTo(ts.findAncestor(d, (n) => ts.isFunctionLike(n) || ts.isSourceFile(n)), this.checker.getSymbolAtLocation(d.name), this.checker);
22
102
  return list.declarations.map((d) => this.declaration(d, constant || once(d), lowered)).join('\n');
23
103
  },
24
- /** An `optionalVariable`'s initializer stored as the optional `type`: a read converting undefined gives that undefined. */
25
- heldStore(d, type) {
26
- const code = this.stored(d.initializer, d, type);
27
- return this.undefinedConverted(code) ?? code;
28
- },
29
104
  declaration(d, constant, lowered) {
30
105
  const i = this.indent;
31
106
  const extension = this.native?.extensionClass(d);
@@ -175,6 +250,12 @@ export const declarationsMethods = {
175
250
  const read = (this.isAny(d.initializer) || this.untypedElement(d.initializer)) && !isUntyped(spelledType(t)) ? (this.checkedPlacement(d.initializer, optionalType(t), maybe, this.storeSlot(d.initializer, optionalType(t), d)) ?? this.fromAny(maybe, optionalType(t))) : this.nullableArrayAs(maybe, this.typeOf(d.initializer), t);
176
251
  return `${i}${constant ? 'val' : 'var'} ${name}: ${optionalType(t)} = ${read}`;
177
252
  }
253
+ if (!this.library && !constant && !lowered && !this.asyncCtx && t === 'String' && this.isStringBuilderLocal(d)) {
254
+ const sym = this.checker.getSymbolAtLocation(d.name);
255
+ this.stringBuilders.add(sym);
256
+ const init = this.stored(d.initializer, d, 'String');
257
+ return `${i}val ${name} = StringBuilder(${init === '""' ? '' : init})`;
258
+ }
178
259
  // An untyped value asserted a Java class its uses need only a superclass of: held as that class, unchecked as script's assertion is.
179
260
  const wider = !this.library && ts.isIdentifier(d.name) ? this.widerAsserted(d) : null;
180
261
  if (wider) {
@@ -423,10 +504,6 @@ export const declarationsMethods = {
423
504
  return this.undefinedAs(slot.raw, t);
424
505
  return `(${slot.raw} ?: ${t === 'Double' ? '0.0' : t === 'String' ? '"null"' : 'false'})`;
425
506
  },
426
- /** The slot of the await `e` is, where its continuation holds the value nullable. */
427
- awaited(e) {
428
- return this.awaitSlots.get(ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses));
429
- },
430
507
  noteNullVar(d) {
431
508
  const init = d.initializer && ts.skipOuterExpressions(d.initializer, ts.OuterExpressionKinds.Parentheses);
432
509
  const sym = ts.isIdentifier(d.name) ? this.resolve(d.name) : undefined;
@@ -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;