@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
@@ -262,3 +262,32 @@ export function droppedProtocolMemberNames(checker, cls, protocols, implemented,
262
262
  }
263
263
  return out;
264
264
  }
265
+ /** Whether dotted version `a` is newer than `b` (when `preferStable` is set, releases without `-` outrank prereleases). */
266
+ export function newerVersion(a, b, preferStable = false) {
267
+ if (preferStable) {
268
+ const sa = !/-/.test(a), sb = !/-/.test(b);
269
+ if (sa !== sb)
270
+ return sa;
271
+ }
272
+ const key = (v) => (v.match(/\d+/g) ?? []).map(Number);
273
+ const ka = key(a), kb = key(b);
274
+ for (let i = 0; i < Math.max(ka.length, kb.length); i++)
275
+ if ((ka[i] ?? 0) !== (kb[i] ?? 0))
276
+ return (ka[i] ?? 0) > (kb[i] ?? 0);
277
+ return false;
278
+ }
279
+ /** The unwrapped initializer of an untyped variable declaration reached from `n` (declaration or identifier), or null. */
280
+ export function untypedVariableInitializer(n, resolve) {
281
+ const d = ts.isVariableDeclaration(n) ? n : ts.isIdentifier(n) ? (ts.isVariableDeclaration(n.parent) && n.parent.name === n ? n.parent : resolve(n)?.valueDeclaration) : undefined;
282
+ return d && ts.isVariableDeclaration(d) && !d.type && d.initializer ? ts.skipOuterExpressions(d.initializer, ts.OuterExpressionKinds.Parentheses) : null;
283
+ }
284
+ /** Whether a built-in primitive constructor value (`Number`, `String`, `Boolean`) is a singleton constructor reference (`jsNumberConstructor`) or a typed converter slot. */
285
+ export function builtinConstructorSlot(e, checker, isUntypedContext) {
286
+ const context = checker.getContextualType(e);
287
+ const slot = context && checker.getNonNullableType(context).getCallSignatures()[0];
288
+ if (slot)
289
+ return { slot };
290
+ const p = e.parent;
291
+ const untyped = (!!context && isUntypedContext(context)) || (ts.isBinaryExpression(p) && [ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken].includes(p.operatorToken.kind));
292
+ return untyped ? { singleton: `js${e.text}Constructor` } : {};
293
+ }
@@ -0,0 +1,144 @@
1
+ // Backend-neutral lowered expression IR foundation: classifies JavaScript operators and expression shapes once in
2
+ // semantics/ so both Swift and Kotlin backends spell from one plan rather than duplicating operator dispatch trees.
3
+ import ts from 'typescript';
4
+ const K = ts.SyntaxKind;
5
+ const RELATIONAL_OPS = {
6
+ [K.LessThanToken]: '<',
7
+ [K.GreaterThanToken]: '>',
8
+ [K.LessThanEqualsToken]: '<=',
9
+ [K.GreaterThanEqualsToken]: '>=',
10
+ };
11
+ const ARITHMETIC_OPS = {
12
+ [K.PlusToken]: { sym: '+', assigns: false },
13
+ [K.MinusToken]: { sym: '-', assigns: false },
14
+ [K.AsteriskToken]: { sym: '*', assigns: false },
15
+ [K.SlashToken]: { sym: '/', assigns: false },
16
+ [K.PercentToken]: { sym: '%', assigns: false },
17
+ [K.AsteriskAsteriskToken]: { sym: '**', assigns: false },
18
+ [K.PlusEqualsToken]: { sym: '+', assigns: true },
19
+ [K.MinusEqualsToken]: { sym: '-', assigns: true },
20
+ [K.AsteriskEqualsToken]: { sym: '*', assigns: true },
21
+ [K.SlashEqualsToken]: { sym: '/', assigns: true },
22
+ [K.PercentEqualsToken]: { sym: '%', assigns: true },
23
+ [K.AsteriskAsteriskEqualsToken]: { sym: '**', assigns: true },
24
+ };
25
+ const LOGICAL_ASSIGN_OPS = {
26
+ [K.QuestionQuestionEqualsToken]: '??=',
27
+ [K.BarBarEqualsToken]: '||=',
28
+ [K.AmpersandAmpersandEqualsToken]: '&&=',
29
+ };
30
+ /** Classifies `<`, `>`, `<=`, `>=` once for both backends: string comparison, dynamic runtime helper, or numeric infix. */
31
+ export function planRelational(op, leftString, rightString, dynamicOperand) {
32
+ const sym = RELATIONAL_OPS[op];
33
+ if (!sym)
34
+ return null;
35
+ if (leftString && rightString)
36
+ return { kind: 'string', op: sym };
37
+ if (dynamicOperand)
38
+ return { kind: 'dynamic', op: sym };
39
+ return { kind: 'numeric', op: sym };
40
+ }
41
+ /** Classifies `+`, `-`, `*`, `/`, `%`, `**` and their compound assignments (`+=`, etc.) once for both backends. */
42
+ export function planArithmetic(op, leftString, rightString, leftAny, rightAny) {
43
+ const entry = ARITHMETIC_OPS[op];
44
+ if (!entry)
45
+ return null;
46
+ if (entry.sym === '+') {
47
+ if (!entry.assigns && (leftString || rightString))
48
+ return { kind: 'concat', assigns: false };
49
+ if (entry.assigns && leftString)
50
+ return { kind: 'concat', assigns: true };
51
+ if (leftAny || (!entry.assigns && rightAny))
52
+ return { kind: 'dynamicAdd', assigns: entry.assigns };
53
+ }
54
+ return { kind: 'numeric', op: entry.sym, assigns: entry.assigns };
55
+ }
56
+ /** Classifies `??=`, `||=`, `&&=`. */
57
+ export function planLogicalAssign(op) {
58
+ const sym = LOGICAL_ASSIGN_OPS[op];
59
+ return sym ? { kind: 'logicalAssign', op: sym } : null;
60
+ }
61
+ /** Classifies `!`, `-`, `+`, `~` prefix unary operators. */
62
+ export function planUnary(op, isBigInt) {
63
+ switch (op) {
64
+ case K.ExclamationToken:
65
+ return { kind: 'not' };
66
+ case K.MinusToken:
67
+ return { kind: 'negate', bigInt: isBigInt };
68
+ case K.PlusToken:
69
+ return { kind: 'plus' };
70
+ case K.TildeToken:
71
+ return { kind: 'bitNot', bigInt: isBigInt };
72
+ default:
73
+ return null;
74
+ }
75
+ }
76
+ /** Flattens left-nested string `+` concatenation chains into an ordered list of leaf operands for builder/buffer emission. */
77
+ export function flattenStringConcat(expr, isString) {
78
+ const out = [];
79
+ const visit = (x) => {
80
+ const inner = ts.skipParentheses(x);
81
+ if (ts.isBinaryExpression(inner) && inner.operatorToken.kind === K.PlusToken && (isString(inner.left) || isString(inner.right))) {
82
+ visit(inner.left);
83
+ visit(inner.right);
84
+ return;
85
+ }
86
+ out.push(x);
87
+ };
88
+ visit(expr);
89
+ return out;
90
+ }
91
+ /** Classifies `===`, `!==`, `==`, `!=` into nullish comparison, dynamic runtime helper, or direct backend comparison. */
92
+ export function planEquality(op, leftAny, rightAny, leftNullish, rightNullish) {
93
+ let kind;
94
+ let negated;
95
+ switch (op) {
96
+ case K.EqualsEqualsEqualsToken:
97
+ kind = 'strict';
98
+ negated = false;
99
+ break;
100
+ case K.ExclamationEqualsEqualsToken:
101
+ kind = 'strict';
102
+ negated = true;
103
+ break;
104
+ case K.EqualsEqualsToken:
105
+ kind = 'loose';
106
+ negated = false;
107
+ break;
108
+ case K.ExclamationEqualsToken:
109
+ kind = 'loose';
110
+ negated = true;
111
+ break;
112
+ default:
113
+ return null;
114
+ }
115
+ if (leftNullish || rightNullish)
116
+ return { kind, negated, mode: 'nullish' };
117
+ if (leftAny || rightAny || kind === 'loose')
118
+ return { kind, negated, mode: 'dynamic' };
119
+ return { kind, negated, mode: 'direct' };
120
+ }
121
+ /** Classifies `a ?? b` based on whether the left operand is untyped, optional, or statically present. */
122
+ export function planNullishCoalesce(leftAny, leftOptional) {
123
+ if (leftAny)
124
+ return { kind: 'dynamic' };
125
+ if (leftOptional)
126
+ return { kind: 'optional' };
127
+ return { kind: 'identity' };
128
+ }
129
+ /** Extracts `typeof x === 'tag'` (or `!==`, `==`, `!=`, in either operand order) into a backend-neutral descriptor. */
130
+ export function typeofComparison(e) {
131
+ const op = e.operatorToken.kind;
132
+ const strict = op === K.EqualsEqualsEqualsToken || op === K.ExclamationEqualsEqualsToken;
133
+ const loose = op === K.EqualsEqualsToken || op === K.ExclamationEqualsToken;
134
+ if (!strict && !loose)
135
+ return null;
136
+ const negated = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
137
+ const left = ts.skipParentheses(e.left);
138
+ const right = ts.skipParentheses(e.right);
139
+ if (ts.isTypeOfExpression(left) && ts.isStringLiteralLike(right))
140
+ return { operand: left.expression, tag: right.text, negated, strict };
141
+ if (ts.isTypeOfExpression(right) && ts.isStringLiteralLike(left))
142
+ return { operand: right.expression, tag: left.text, negated, strict };
143
+ return null;
144
+ }
@@ -1,7 +1,9 @@
1
- // The async lowering's state and identical placement/refusal forwarding methods both translators keep alike, installed on
2
- // each prototype as `frontMethods` are. Not traced: they answer nothing.
1
+ // The async lowering's state and identical placement/refusal/translator forwarding methods both translators keep alike,
2
+ // installed on each prototype as `frontMethods` are. Not traced: they answer nothing.
3
3
  import ts from 'typescript';
4
- import { argumentSlot, place, resultSlot, storeSlot } from "./placement.js";
4
+ import { thisNodes } from "./ast.js";
5
+ import { isConstant } from "./lang.js";
6
+ import { argumentSlot, observerSlot, place, resultSlot, storeSlot } from "./placement.js";
5
7
  import { located } from "./refusals.js";
6
8
  export const loweringMethods = {
7
9
  /** Runs `body` inside a lowered async region: its breaks and continues are the region's, not a native loop's. */
@@ -95,4 +97,119 @@ export const loweringMethods = {
95
97
  const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
96
98
  return this.config.refusals.limitAt(sf.fileName, line + 1, character + 1, what, n.getText().slice(0, 80), id);
97
99
  },
100
+ /** Runs `body` indented one level deeper. */
101
+ nested(body) {
102
+ const saved = this.indent;
103
+ this.indent += ' ';
104
+ try {
105
+ return body();
106
+ }
107
+ finally {
108
+ this.indent = saved;
109
+ }
110
+ },
111
+ /** A statement or block formatted as `{ ... }` indented from `base`. */
112
+ block(b, base) {
113
+ if (base === undefined)
114
+ base = this.indent;
115
+ const saved = this.indent;
116
+ this.indent = base + ' ';
117
+ try {
118
+ const body = this.statements(ts.isBlock(b) ? [...b.statements] : [b]);
119
+ return `{\n${body.join('\n')}\n${base}}`;
120
+ }
121
+ finally {
122
+ this.indent = saved;
123
+ }
124
+ },
125
+ /** The slot of the await `e` is, where its continuation holds the value optional. */
126
+ awaited(e) {
127
+ return this.awaitSlots.get(ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses));
128
+ },
129
+ /** The callee's text for a call expression, else empty. */
130
+ calleeName(e) {
131
+ return ts.isCallExpression(e) ? e.expression.getText() : '';
132
+ },
133
+ /** App/plugin read of a primitive that converted undefined (`(x ?? "undefined")`): the optional it converts, or null. */
134
+ convertedOptional(e, t) {
135
+ if (this.library)
136
+ return null;
137
+ const inner = ts.skipOuterExpressions(e);
138
+ const opt = t.endsWith('?') ? t : `${t}?`;
139
+ if (ts.isConditionalExpression(inner) && this.typeOf(inner) === t && [inner.whenTrue, inner.whenFalse].some((x) => this.undefinedConverted(this.coerce(ts.skipOuterExpressions(x, ts.OuterExpressionKinds.Parentheses), t))))
140
+ return this.coerce(inner, opt);
141
+ return this.undefinedConverted(this.expr(ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses)));
142
+ },
143
+ /** An `optionalVariable`'s initializer stored as the optional `type`: a read converting undefined gives that undefined. */
144
+ heldStore(d, type) {
145
+ const code = this.stored(d.initializer, d, type);
146
+ return this.undefinedConverted(code) ?? code;
147
+ },
148
+ /** The kit class a mixin class (`applyMixins(View, [Extended])`) is applied to. */
149
+ mixinOf(sym) {
150
+ const d = sym?.valueDeclaration;
151
+ return d && ts.isClassDeclaration(d) ? this.patterns.mixinTarget(d) : null;
152
+ },
153
+ /** A `nullishRead` value as its `JSNullish<T>`. */
154
+ nullishCode(e) {
155
+ if (!ts.isCallExpression(e) && !ts.isPropertyAccessExpression(e))
156
+ return this.refName(e);
157
+ this.nullishCalls.add(e);
158
+ try {
159
+ return this.expr(e);
160
+ }
161
+ finally {
162
+ this.nullishCalls.delete(e);
163
+ }
164
+ },
165
+ /** `x` read by an equality or `typeof` (`ObserverSlot`). */
166
+ observe(x, read = 'untyped') {
167
+ return place(this.placement, x, observerSlot(this.placement, read));
168
+ },
169
+ /** A component created as a root view (bootstrap, route, dialog): made and rendered as the framework makes it. */
170
+ rootView(cls, type, make) {
171
+ return this.framework.hooks.wrapRootView ? this.framework.hooks.wrapRootView(this, cls, type, make) : make;
172
+ },
173
+ /** `fooProperty.setNative`: the registered name of the property it belongs to. */
174
+ setNativeOf(e) {
175
+ if (!ts.isPropertyAccessExpression(e) || e.name.text !== 'setNative')
176
+ return null;
177
+ return this.properties?.name(this.resolve(e.expression)) ?? null;
178
+ },
179
+ /** The declared or aliased symbol name of `e`'s type, or empty. */
180
+ symbolName(e) {
181
+ const t = this.checker.getTypeAtLocation(e);
182
+ return (t.aliasSymbol ?? t.getSymbol())?.getName() ?? '';
183
+ },
184
+ /** A module-level function, class, or variable's emitted top-level name. */
185
+ topName(decl, name) {
186
+ return this.topNames().get(decl) ?? name;
187
+ },
188
+ /** Whether a parameter's initializer can be emitted as a native constant default rather than applied in the body. */
189
+ constantDefault(p) {
190
+ return !!p.initializer && isConstant(p.initializer) && !(this.optionalDefaults && (this.optionalDefaults.has(p) || this.isAny(p.name))) && !this.familyDefaultsDiffer(p) && !this.states.defaultTakesUndefined(p);
191
+ },
192
+ /** Runs `body` with `this` in `fn` (and in the arrow functions inside it) read as `name`. */
193
+ withThis(fn, name, untyped, body) {
194
+ const nodes = thisNodes(fn);
195
+ for (const n of nodes) {
196
+ this.subst.set(n, name);
197
+ if (untyped)
198
+ this.untypedThis.add(n);
199
+ }
200
+ try {
201
+ return body();
202
+ }
203
+ finally {
204
+ for (const n of nodes) {
205
+ this.subst.delete(n);
206
+ this.untypedThis.delete(n);
207
+ }
208
+ }
209
+ },
210
+ /** Refuses a self-referencing named generator expression (`function* f() { yield f; }`). */
211
+ refuseNamedGenerator(fn) {
212
+ if (fn.asteriskToken)
213
+ throw this.error(fn, 'a named function expression', 'named-function-expression');
214
+ },
98
215
  };
@@ -1,3 +1,19 @@
1
+ /** Constructs a structured `EmittedExpr`. */
2
+ export function emitted(code, opts) {
3
+ return { code, throws: opts?.throws ?? false, pure: opts?.pure ?? false, ...(opts?.mark ? { mark: opts.mark } : {}) };
4
+ }
5
+ /** Constructs a pure `EmittedExpr` (evaluating twice equals evaluating once). */
6
+ export function pureExpr(code, mark) {
7
+ return mark ? { code, throws: false, pure: true, mark } : { code, throws: false, pure: true };
8
+ }
9
+ /** Constructs a marked `EmittedExpr`. */
10
+ export function markedExpr(code, mark, opts) {
11
+ return { code, throws: opts?.throws ?? false, pure: opts?.pure ?? false, mark };
12
+ }
13
+ /** Extracts raw code text from either a string or an `EmittedExpr`. */
14
+ export function exprText(expr) {
15
+ return typeof expr === 'string' ? expr : expr.code;
16
+ }
1
17
  /**
2
18
  * What one translation's producers recorded of the code they emitted (its outermost operation, and whether reading it twice
3
19
  * is reading it once), kept by the code: a string carries no fields, and readers get code from `expr`, the conversions and
@@ -8,6 +24,20 @@
8
24
  export class CodeMarks {
9
25
  made = new Map();
10
26
  pureCodes = new Set();
27
+ /** Registers a structured `EmittedExpr` and returns its code string for incremental callers. */
28
+ emit(expr) {
29
+ if (expr.pure)
30
+ this.pureCodes.add(expr.code);
31
+ if (expr.mark || expr.throws)
32
+ this.made.set(expr.code, { code: expr.code, throws: expr.throws, pure: expr.pure || this.pureCodes.has(expr.code), ...(expr.mark ? { mark: expr.mark } : {}) });
33
+ return expr.code;
34
+ }
35
+ /** Reads a structured `EmittedExpr` view of previously emitted code. */
36
+ read(code) {
37
+ if (typeof code !== 'string')
38
+ return code;
39
+ return this.valueOf(code);
40
+ }
11
41
  /** Code, recorded with its outermost operation. */
12
42
  marked(code, mark) {
13
43
  this.made.set(code, { code, throws: false, pure: this.pureCodes.has(code), mark });
@@ -107,7 +107,7 @@ function placed(b, e, target, slot) {
107
107
  throw b.error(e, rule.refuse);
108
108
  // `readHeld` derives the carrier of a name or member read only; any other read's code converts itself.
109
109
  const read = ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses);
110
- const code = rule.rule === 'untyped' && (ts.isIdentifier(read) || ts.isPropertyAccessExpression(read)) ? b.untypedRead(b.expr(e), target) : b.coerceTyped(e, target);
110
+ const code = rule.rule === 'untyped' && (ts.isIdentifier(read) || ts.isPropertyAccessExpression(read)) ? b.untypedRead(b.expr(e), target, e) : b.coerceTyped(e, target);
111
111
  // A slot taking a string, number or boolean's undefined, or any value, takes it as it is, not converted.
112
112
  if (takesUndefined(to)) {
113
113
  const held = b.undefinedConverted(code) ?? (choice !== e && !b.library ? b.undefinedConverted(b.coerceTyped(choice, target)) : null);
@@ -564,9 +564,15 @@ export function assertedReceiverCell(b, target, key) {
564
564
  return { cell: 'asIs' };
565
565
  return receiverCell(b, receiverSlot(target, key));
566
566
  }
567
- /** An element read's receiver cell (`assertedReceiverCell`). */
567
+ /** An element read's receiver cell (`assertedReceiverCell` or `unsafeReceiver`). */
568
568
  export function elementReceiverCell(b, e) {
569
- return ts.isOptionalChain(e) ? { cell: 'asIs' } : assertedReceiverCell(b, e.expression, keyName(e.argumentExpression));
569
+ if (ts.isOptionalChain(e))
570
+ return { cell: 'asIs' };
571
+ const key = keyName(e.argumentExpression);
572
+ const asserted = assertedReceiverCell(b, e.expression, key);
573
+ if (asserted.cell !== 'asIs')
574
+ return asserted;
575
+ return unsafeReceiver(e.expression, b.checker) ? receiverCell(b, receiverSlot(e.expression, key)) : { cell: 'asIs' };
570
576
  }
571
577
  /** The name a TypeError reading by `key` gives: a literal key's text, else the key's source. */
572
578
  export function keyName(key) {
@@ -3,25 +3,27 @@
3
3
  // text a developer reads is here, or in the framework adapter's refusals, and
4
4
  // nowhere else.
5
5
  //
6
- // `limit`: JavaScript a compiled release cannot run by design. `gap`: code
7
- // that runs as JavaScript and the compiler does not translate yet. A rewrite
6
+ // `limit`: fundamentally incompatible with an engine-free AOT release or platform representation.
7
+ // `excluded`: technically implementable in AOT, intentionally excluded to preserve predictable native dispatch and footprint.
8
+ // `gap`: code that runs as JavaScript and the compiler does not translate yet. A rewrite
8
9
  // shown here is one a diff case runs on both backends and matches Node with.
9
10
  import { compiledEnv } from "../program/env.js";
10
11
  const ISOLATE = 'move the code into a plain function of its own with typed parameters and result, so the rest of the module translates; the refusal then names only that function';
11
12
  export const REFUSALS = {
12
- // Preflight: lib globals and syntax with no compiled runtime.
13
- proxy: { class: 'limit', title: 'Proxy', why: 'a compiled release has no JavaScript engine to run its traps', suggestion: 'use a class with explicit getters and setters, or a Map for dynamic keys', before: 'const p = new Proxy(target, { get: (t, k) => t[k] ?? 0 })', after: 'const counts = new Map<string, number>(); const read = (k: string) => counts.get(k) ?? 0' },
14
- reflect: { class: 'limit', title: 'Reflect', suggestion: 'use the operation directly (obj[key], key in obj, Object.keys(obj), new Cls(...args))', before: 'Reflect.has(o, "a"); Reflect.ownKeys(o)', after: '"a" in o; Object.keys(o)' },
13
+ // Preflight: intentionally excluded dynamic/meta-programming & shared-memory features (technically implementable in AOT, excluded by design for predictable native dispatch and footprint).
14
+ proxy: { class: 'excluded', title: 'Proxy', why: 'intentionally excluded to avoid intercepting every native property read and write through trap dispatch', suggestion: 'use a class with explicit getters and setters, or a Map for dynamic keys', before: 'const p = new Proxy(target, { get: (t, k) => t[k] ?? 0 })', after: 'const counts = new Map<string, number>(); const read = (k: string) => counts.get(k) ?? 0' },
15
+ reflect: { class: 'excluded', title: 'Reflect', why: 'intentionally excluded alongside Proxy trap forwarding', suggestion: 'use the operation directly (obj[key], key in obj, Object.keys(obj), new Cls(...args))', before: 'Reflect.has(o, "a"); Reflect.ownKeys(o)', after: '"a" in o; Object.keys(o)' },
16
+ 'finalization-registry': { class: 'excluded', title: 'FinalizationRegistry', why: 'intentionally excluded because ARC and JVM GC timing cannot preserve portable finalizer guarantees', suggestion: 'release the resource explicitly (a dispose() method, or an unloaded/disposeNativeView hook)' },
17
+ 'shared-array-buffer': { class: 'excluded', title: 'SharedArrayBuffer', why: 'intentionally excluded in favor of message-passing and buffer transfer between workers', suggestion: 'use an ArrayBuffer, and post copies or transfers between workers' },
18
+ atomics: { class: 'excluded', title: 'Atomics', why: 'intentionally excluded alongside SharedArrayBuffer', suggestion: 'use an ArrayBuffer and post messages between workers instead of shared memory' },
19
+ 'arguments-callee': { class: 'excluded', title: '`arguments.callee`', why: 'disallowed in strict mode and intentionally excluded', suggestion: 'name the function and call it by its name', before: 'const f = function (n) { return n ? n * arguments.callee(n - 1) : 1; }', after: 'function f(n: number): number { return n ? n * f(n - 1) : 1; }' },
20
+ proto: { class: 'excluded', title: '`__proto__`', why: 'legacy Annex B mutator intentionally excluded in favor of static class hierarchies', suggestion: 'use Object.getPrototypeOf, or a class hierarchy declared in the source', before: 'b.__proto__ === A.prototype', after: 'b instanceof A' },
21
+ // Preflight & representation limits: fundamentally incompatible with an engine-free AOT release or target platform representation.
15
22
  eval: { class: 'limit', title: 'eval', suggestion: 'there is no JavaScript engine to evaluate code: replace it with a lookup of known functions, or keep this app on the JavaScript release', before: 'eval(name + "()")', after: "const actions = new Map<string, () => void>([['save', save], ['load', load]]); actions.get(name)?.()" },
16
23
  'function-constructor': { class: 'limit', title: 'Function from text', suggestion: 'there is no JavaScript engine to compile a function from text: write the function in the source', before: 'new Function("a", "b", "return a + b")', after: '(a: number, b: number) => a + b' },
17
- 'finalization-registry': { class: 'limit', title: 'FinalizationRegistry', suggestion: 'finalizers do not run in a compiled release: release the resource explicitly (a dispose() method, or an unloaded/disposeNativeView hook)' },
18
- 'shared-array-buffer': { class: 'limit', title: 'SharedArrayBuffer', suggestion: 'use an ArrayBuffer, and post copies between workers' },
19
- atomics: { class: 'limit', title: 'Atomics', suggestion: 'use an ArrayBuffer and post messages between workers instead of shared memory' },
20
24
  with: { class: 'limit', title: '`with`', suggestion: 'name the object explicitly (`obj.x` instead of `x` inside `with (obj)`)' },
21
25
  'computed-import': { class: 'limit', title: 'import() of a computed specifier', suggestion: "import each module by a literal path (`() => import('./pages/a')`), and choose among those functions at run time" },
22
26
  'computed-require': { class: 'limit', title: 'require() of a computed specifier', suggestion: 'require each module by a literal path, and choose among them at run time' },
23
- 'arguments-callee': { class: 'limit', title: '`arguments.callee`', suggestion: 'name the function and call it by its name', before: 'const f = function (n) { return n ? n * arguments.callee(n - 1) : 1; }', after: 'function f(n: number): number { return n ? n * f(n - 1) : 1; }' },
24
- proto: { class: 'limit', title: '`__proto__`', suggestion: 'use Object.getPrototypeOf, or a class hierarchy declared in the source', before: 'b.__proto__ === A.prototype', after: 'b instanceof A' },
25
27
  'process-env': { class: 'limit', title: 'process.env the bundler did not define', suggestion: 'a compiled release has no process environment: define the variable in the bundler config (Vite `define`, webpack DefinePlugin), which the compiled build reads too' },
26
28
  'undefined-constant': { class: 'limit', title: 'a bundler constant declared but never given a value', suggestion: 'if your bundler defines it (Vite `define`, webpack DefinePlugin), the compiled build reads the same config: check the name there; otherwise assign globalThis.NAME before it is read' },
27
29
  'shared-typed-copy': { class: 'limit', title: 'an array of one object type converted into an array of another, a copy where JavaScript shares it', suggestion: 'declare the value with the wanted type where it is made, or copy it explicitly (`list.map((x) => ({ ...x }))`)' },
@@ -51,7 +53,6 @@ export const REFUSALS = {
51
53
  'class-expression': { class: 'gap', title: 'a class expression', suggestion: 'declare the class with a name, then use it', before: 'const o = new (class { x = 1; })()', after: 'class Point { x = 1; } const o = new Point()' },
52
54
  'named-function-expression': { class: 'gap', title: 'a named function expression that refers to itself', suggestion: 'declare it as a function declaration and refer to that name', before: 'const g = function f(n) { return n ? f(n - 1) : 0; }', after: 'function f(n: number): number { return n ? f(n - 1) : 0; } const g = f' },
53
55
  'unsupported-base': { class: 'gap', title: 'a class extending null, Function or another base the compiler does not extend yet', suggestion: 'declare the class without that base: hold a function in a field and call it, or use Object.create(null) for an object without a prototype', before: 'class Fn extends Function { constructor() { super(); } }', after: 'class Fn { constructor(readonly call: () => number) {} }' },
54
- worker: { class: 'gap', title: 'a Worker in an iOS build', suggestion: "the iOS kit starts no workers yet (Android's does): run the work on the main thread in slices (a setTimeout per batch), or in native code on a background queue, and post its result back" },
55
56
  'delete-member': { class: 'gap', title: 'delete of this member', suggestion: 'keep entries that come and go in a Map (map.delete(key)), or make the field optional and assign undefined', before: 'delete this.cache[key]', after: 'this.cache.delete(key) // cache: Map<string, T>' },
56
57
  'index-type': { class: 'gap', title: 'indexing this type', suggestion: 'give the indexed object a Record or Map type, or read the member by its name', before: '(obj as any)[key]', after: 'const table: Record<string, number> = obj; table[key]' },
57
58
  native: { class: 'gap', title: 'a native API the compiler does not call yet', suggestion: ISOLATE },
@@ -164,3 +164,14 @@ export function propSignal(e, checker, framework) {
164
164
  const kind = name === undefined ? undefined : framework.signalKind(name);
165
165
  return kind === 'input' || kind === 'model';
166
166
  }
167
+ /** Whether `n` declares or references an untyped variable initialized from a read of a signal holding null (`const card = this.morning()`). */
168
+ export function isGivenNullSignalValue(n, resolve, isNullSignalRead) {
169
+ const d = (ts.isVariableDeclaration(n.parent) && n.parent.name === n ? n.parent : ts.isIdentifier(n) ? resolve(n)?.valueDeclaration : undefined);
170
+ if (!d || !ts.isVariableDeclaration(d) || d.type || !d.initializer)
171
+ return false;
172
+ return isNullSignalRead(d.initializer);
173
+ }
174
+ /** Whether a class property declaration initializes a read-only signal via memoization or `.asReadonly()`. */
175
+ export function isReadonlySignalProperty(decl, checker, framework, callee) {
176
+ return !!framework.memoized(decl, checker) || /\.asReadonly$/.test(callee);
177
+ }
@@ -239,6 +239,13 @@ export const missingMethods = {
239
239
  */
240
240
  widenedObject(x) {
241
241
  const results = (e) => {
242
+ if (ts.isAwaitExpression(e)) {
243
+ const inner = ts.skipOuterExpressions(e.expression, ts.OuterExpressionKinds.Parentheses);
244
+ if (!ts.isCallExpression(inner))
245
+ return [];
246
+ const d = this.checker.getResolvedSignature(inner)?.getDeclaration();
247
+ return d && !ts.isJSDocSignature(d) && (this.lenientAsync(d) || !this.appCode(d)) ? [d] : [];
248
+ }
242
249
  if (!ts.isCallExpression(e))
243
250
  return [];
244
251
  const d = this.checker.getResolvedSignature(e)?.getDeclaration();
@@ -1,16 +1,151 @@
1
- // Module-level `let`/`const` bindings belonging to an import cycle, which may be read or written before their
2
- // initializer runs (JavaScript's TDZ ReferenceError). Only cyclic app modules carry TDZ guards so acyclic modules
3
- // and library kits emit zero extra overhead.
1
+ // Module-level `let`/`const` bindings that may be read or written before their initializer runs (JavaScript's TDZ
2
+ // ReferenceError): either belonging to an import cycle or read by a function / earlier statement in the same module
3
+ // when executable code runs before the declaration. Other module bindings and library kits emit zero extra overhead.
4
4
  import ts from 'typescript';
5
- import { hasModifier } from "./ast.js";
5
+ import { hasModifier, resolveSymbol } from "./ast.js";
6
+ /** Whether a top-level statement before a declaration can run user code (and thus invoke a hoisted function or closure). */
7
+ function canRunCode(st) {
8
+ if (ts.isImportDeclaration(st) || ts.isExportDeclaration(st) || ts.isFunctionDeclaration(st) || ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isEmptyStatement(st))
9
+ return false;
10
+ if (hasModifier(st, ts.SyntaxKind.DeclareKeyword))
11
+ return false;
12
+ if (ts.isVariableStatement(st))
13
+ return st.declarationList.declarations.some((d) => !!d.initializer && exprCanRunCode(d.initializer));
14
+ if (ts.isClassDeclaration(st))
15
+ return st.members.some((m) => ts.isClassStaticBlockDeclaration(m) || (ts.isPropertyDeclaration(m) && !!(ts.getCombinedModifierFlags(m) & ts.ModifierFlags.Static) && !!m.initializer && exprCanRunCode(m.initializer)));
16
+ return true;
17
+ }
18
+ /** Whether an expression may invoke a function, getter, constructor, or other non-literal code at evaluation time. */
19
+ function exprCanRunCode(e) {
20
+ if (ts.isLiteralExpression(e) || e.kind === ts.SyntaxKind.TrueKeyword || e.kind === ts.SyntaxKind.FalseKeyword || e.kind === ts.SyntaxKind.NullKeyword || ts.isArrowFunction(e) || ts.isFunctionExpression(e) || ts.isIdentifier(e))
21
+ return false;
22
+ if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isTypeAssertionExpression(e) || ts.isSatisfiesExpression(e) || ts.isNonNullExpression(e))
23
+ return exprCanRunCode(e.expression);
24
+ if (ts.isPrefixUnaryExpression(e))
25
+ return exprCanRunCode(e.operand);
26
+ if (ts.isBinaryExpression(e))
27
+ return exprCanRunCode(e.left) || exprCanRunCode(e.right);
28
+ if (ts.isArrayLiteralExpression(e))
29
+ return e.elements.some((x) => !ts.isOmittedExpression(x) && exprCanRunCode(ts.isSpreadElement(x) ? x.expression : x));
30
+ if (ts.isObjectLiteralExpression(e))
31
+ return e.properties.some((p) => (ts.isPropertyAssignment(p) && exprCanRunCode(p.initializer)) || (ts.isSpreadAssignment(p) && exprCanRunCode(p.expression)));
32
+ return true;
33
+ }
34
+ /** Collects same-module `let`/`const` declarations that may be observed before their initializer executes. */
35
+ function addSameModuleTdz(checker, sf, out) {
36
+ const decls = new Map();
37
+ for (let i = 0; i < sf.statements.length; i++) {
38
+ const st = sf.statements[i];
39
+ if (!ts.isVariableStatement(st) || hasModifier(st, ts.SyntaxKind.DeclareKeyword))
40
+ continue;
41
+ if (!(st.declarationList.flags & ts.NodeFlags.BlockScoped))
42
+ continue;
43
+ for (let j = 0; j < st.declarationList.declarations.length; j++) {
44
+ const d = st.declarationList.declarations[j];
45
+ if (!ts.isIdentifier(d.name) || !d.initializer || out.has(d))
46
+ continue;
47
+ const sym = checker.getSymbolAtLocation(d.name);
48
+ if (sym)
49
+ decls.set(sym, { decl: d, stmtIndex: i, declIndex: j });
50
+ }
51
+ }
52
+ if (!decls.size)
53
+ return;
54
+ // Track which hoisted function declarations are reachable from executable statements before each statement index.
55
+ const hoistedFns = new Map();
56
+ for (const st of sf.statements) {
57
+ if (ts.isFunctionDeclaration(st) && st.name && st.body) {
58
+ const sym = checker.getSymbolAtLocation(st.name);
59
+ if (sym)
60
+ hoistedFns.set(sym, st);
61
+ }
62
+ }
63
+ const isRef = (n) => {
64
+ const p = n.parent;
65
+ if (ts.isImportSpecifier(p) || ts.isExportSpecifier(p) || ts.isImportClause(p) || ts.isTypeReferenceNode(p))
66
+ return false;
67
+ if (ts.isVariableDeclaration(p) && p.name === n)
68
+ return false;
69
+ if (ts.isPropertyAccessExpression(p) && p.name === n)
70
+ return false;
71
+ if ((ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p) || ts.isPropertyDeclaration(p)) && p.name === n)
72
+ return false;
73
+ return true;
74
+ };
75
+ const referencedFnsIn = (root) => {
76
+ const refs = new Set();
77
+ const visit = (n) => {
78
+ if (ts.isIdentifier(n) && isRef(n)) {
79
+ const sym = resolveSymbol(n, checker);
80
+ if (sym && hoistedFns.has(sym))
81
+ refs.add(sym);
82
+ }
83
+ ts.forEachChild(n, visit);
84
+ };
85
+ ts.forEachChild(root, visit);
86
+ return refs;
87
+ };
88
+ const fnCalls = new Map();
89
+ for (const [sym, fn] of hoistedFns)
90
+ fnCalls.set(sym, referencedFnsIn(fn.body));
91
+ const closeReach = (seeds) => {
92
+ const reached = new Set(seeds);
93
+ const queue = [...seeds];
94
+ while (queue.length) {
95
+ const cur = queue.pop();
96
+ for (const next of fnCalls.get(cur) ?? []) {
97
+ if (!reached.has(next)) {
98
+ reached.add(next);
99
+ queue.push(next);
100
+ }
101
+ }
102
+ }
103
+ return reached;
104
+ };
105
+ const reachableFnsBefore = new Array(sf.statements.length);
106
+ const seenBefore = new Set();
107
+ for (let i = 0; i < sf.statements.length; i++) {
108
+ reachableFnsBefore[i] = closeReach(seenBefore);
109
+ const st = sf.statements[i];
110
+ if (!ts.isFunctionDeclaration(st) && canRunCode(st)) {
111
+ for (const s of referencedFnsIn(st))
112
+ seenBefore.add(s);
113
+ }
114
+ }
115
+ const walk = (node, stmtIndex, hoistedSym, inDeferredScope) => {
116
+ if (ts.isIdentifier(node) && isRef(node)) {
117
+ const sym = resolveSymbol(node, checker);
118
+ const entry = sym ? decls.get(sym) : undefined;
119
+ if (entry) {
120
+ const beforeDecl = stmtIndex < entry.stmtIndex;
121
+ const inOwnInit = !inDeferredScope && stmtIndex === entry.stmtIndex && node.pos >= entry.decl.initializer.pos && node.end <= entry.decl.initializer.end;
122
+ const fnReachableEarly = !!hoistedSym && reachableFnsBefore[entry.stmtIndex].has(hoistedSym);
123
+ if ((beforeDecl && !inDeferredScope) || fnReachableEarly || inOwnInit) {
124
+ out.add(entry.decl);
125
+ }
126
+ }
127
+ }
128
+ const entersDeferred = ts.isFunctionLike(node) || ts.isClassStaticBlockDeclaration(node);
129
+ ts.forEachChild(node, (child) => walk(child, stmtIndex, hoistedSym, inDeferredScope || entersDeferred));
130
+ };
131
+ for (let i = 0; i < sf.statements.length; i++) {
132
+ const st = sf.statements[i];
133
+ const hoistedSym = ts.isFunctionDeclaration(st) && st.name ? (checker.getSymbolAtLocation(st.name) ?? null) : null;
134
+ walk(st, i, hoistedSym, false);
135
+ }
136
+ }
6
137
  /**
7
- * The module-level `let` and `const` declarations (with initializers) in `files` that belong to an import cycle
8
- * (SCC of size > 1 or self-import in the value-import graph).
138
+ * The module-level `let` and `const` declarations (with initializers) in `files` that may be read or written before
139
+ * their initializer runs: either in an import cycle (SCC of size > 1 or self-import) or reachable before initialization
140
+ * within the same module.
9
141
  */
10
142
  export function cyclicModuleBindings(checker, files) {
11
143
  const sources = files.filter((f) => !f.isDeclarationFile);
144
+ const out = new Set();
145
+ for (const sf of sources)
146
+ addSameModuleTdz(checker, sf, out);
12
147
  if (sources.length < 2)
13
- return new Set();
148
+ return out;
14
149
  const fileSet = new Set(sources);
15
150
  const edges = new Map();
16
151
  const resolveTargets = (sf, seen) => {
@@ -89,7 +224,6 @@ export function cyclicModuleBindings(checker, files) {
89
224
  for (const sf of sources)
90
225
  if (!index.has(sf))
91
226
  strongConnect(sf);
92
- const out = new Set();
93
227
  for (const sf of cyclic) {
94
228
  for (const st of sf.statements) {
95
229
  if (!ts.isVariableStatement(st) || hasModifier(st, ts.SyntaxKind.DeclareKeyword))
@@ -460,7 +460,7 @@ export class Throws {
460
460
  return true;
461
461
  if (ts.isPropertyAccessExpression(n) && !n.questionDotToken && unsafeReceiver(n.expression, c))
462
462
  return true;
463
- if (ts.isElementAccessExpression(n) && !n.questionDotToken && ts.isOptionalChain(n) && unsafeReceiver(n.expression, c))
463
+ if (ts.isElementAccessExpression(n) && !n.questionDotToken && unsafeReceiver(n.expression, c))
464
464
  return true;
465
465
  if ((ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n)) && !n.questionDotToken && uncheckedMatch(n.expression, c))
466
466
  return true;