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

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 (71) hide show
  1. package/dist/kit/kit-index.js +9 -0
  2. package/dist/kotlin/access.js +7 -9
  3. package/dist/kotlin/arguments.js +2 -2
  4. package/dist/kotlin/class-accessors.js +1 -1
  5. package/dist/kotlin/class-declaration.js +23 -2
  6. package/dist/kotlin/class-methods.js +21 -11
  7. package/dist/kotlin/components.js +2 -7
  8. package/dist/kotlin/core-api.js +2 -21
  9. package/dist/kotlin/declarations.js +86 -9
  10. package/dist/kotlin/functions.js +1 -4
  11. package/dist/kotlin/global-calls.js +1 -4
  12. package/dist/kotlin/literals.js +3 -6
  13. package/dist/kotlin/names.js +2 -0
  14. package/dist/kotlin/native/classfiles.js +2 -13
  15. package/dist/kotlin/operators.js +12 -6
  16. package/dist/kotlin/optional-chains.js +2 -9
  17. package/dist/kotlin/overrides.js +3 -15
  18. package/dist/kotlin/placement.js +1 -12
  19. package/dist/kotlin/statements.js +1 -13
  20. package/dist/kotlin/translator.js +2 -10
  21. package/dist/kotlin/type-tests.js +1 -1
  22. package/dist/kotlin/types.js +2 -19
  23. package/dist/program/core-facts.js +9 -0
  24. package/dist/semantics/facts.js +37 -1
  25. package/dist/semantics/forms/by-name.js +18 -4
  26. package/dist/semantics/lang.js +36 -1
  27. package/dist/semantics/lower.js +90 -0
  28. package/dist/semantics/lowering-methods.js +115 -3
  29. package/dist/semantics/marks.js +30 -0
  30. package/dist/semantics/refusals.js +12 -11
  31. package/dist/semantics/tdz.js +103 -8
  32. package/dist/swift/access.js +6 -8
  33. package/dist/swift/assignment.js +10 -2
  34. package/dist/swift/calls.js +7 -2
  35. package/dist/swift/class-accessors.js +1 -1
  36. package/dist/swift/class-declaration.js +3 -2
  37. package/dist/swift/class-methods.js +16 -1
  38. package/dist/swift/classes.js +23 -9
  39. package/dist/swift/components.js +0 -4
  40. package/dist/swift/core-api.js +9 -29
  41. package/dist/swift/declarations.js +0 -5
  42. package/dist/swift/expression-statements.js +7 -0
  43. package/dist/swift/global-calls.js +0 -4
  44. package/dist/swift/lenient.js +3 -5
  45. package/dist/swift/method-values.js +1 -19
  46. package/dist/swift/modules.js +2 -0
  47. package/dist/swift/names.js +0 -9
  48. package/dist/swift/native/api.js +3 -1
  49. package/dist/swift/native/dispatch.js +2 -8
  50. package/dist/swift/operators.js +7 -6
  51. package/dist/swift/optional-chains.js +1 -8
  52. package/dist/swift/parameters.js +0 -4
  53. package/dist/swift/placement.js +7 -12
  54. package/dist/swift/protocols.js +25 -4
  55. package/dist/swift/results.js +0 -4
  56. package/dist/swift/statements.js +1 -13
  57. package/dist/swift/translator.js +0 -10
  58. package/dist/types/adapter-api.d.ts +3 -3
  59. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Array.kt +53 -12
  60. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/JSON.kt +30 -4
  61. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Language.kt +33 -0
  62. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +9 -1
  63. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Values.kt +137 -28
  64. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +17 -0
  65. package/kit-apple/Sources/NativeScriptKit/Core/color.index.ios.swift +60 -0
  66. package/kit-apple/Sources/NativeScriptKit/Core/js-libs.easysax.easysax.swift +24 -6
  67. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +3 -3
  68. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.gestures-common.swift +2 -0
  69. package/kit-apple/Sources/NativeScriptKit/Runtime/JSON.swift +151 -82
  70. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +13 -1
  71. package/package.json +1 -1
@@ -96,17 +96,7 @@ export const overridesMethods = {
96
96
  e = e.expression;
97
97
  return ts.isIdentifier(e) && (e.text === 'global' || e.text === 'globalThis') && (this.resolve(e)?.declarations ?? []).every((d) => d.getSourceFile().isDeclarationFile);
98
98
  },
99
- /** `fooProperty.setNative`: the registered name of the property it belongs to. */
100
- setNativeOf(e) {
101
- if (!ts.isPropertyAccessExpression(e) || e.name.text !== 'setNative')
102
- return null;
103
- return this.properties?.name(this.resolve(e.expression)) ?? null;
104
- },
105
- /** The kit class a mixin class (`applyMixins(View, [Extended])`) is applied to. */
106
- mixinOf(sym) {
107
- const d = sym?.valueDeclaration;
108
- return d && ts.isClassDeclaration(d) ? this.patterns.mixinTarget(d) : null;
109
- },
99
+ /* setNativeOf and mixinOf are installed from semantics/lowering-methods.ts */
110
100
  /**
111
101
  * A method overriding kit-android's: the kit's Kotlin signature, the
112
102
  * TypeScript body seeing its own types; what it throws is reported, as an
@@ -227,7 +217,7 @@ export const overridesMethods = {
227
217
  return this.library.counterpart(file, name) ?? 'null';
228
218
  },
229
219
  /** Whether a compiled class or one it extends declares a member of this name. */
230
- compiledMember(cls, name) {
220
+ declaresCompiledMember(cls, name) {
231
221
  for (let b = cls; b; b = programBase(b, this.checker))
232
222
  if (b.members.some((m) => m.name?.getText() === name) || this.facts.prototypeKeys().data.has(name) || this.facts.prototypeKeys().accessors.has(name))
233
223
  return true;
@@ -595,9 +585,7 @@ export const overridesMethods = {
595
585
  return target.name;
596
586
  },
597
587
  /** A module-level function, class or variable's Kotlin name. */
598
- topName(decl, name) {
599
- return this.topNames().get(decl) ?? name;
600
- },
588
+ /* topName is installed from semantics/lowering-methods.ts */
601
589
  /**
602
590
  * App mode: a type name Kotlin code already has unqualified (a default import's, the runtime's, a thread annotation's,
603
591
  * whose import outranks the app's package). Java classes are spelled qualified, so their names hide nothing.
@@ -43,18 +43,7 @@ export const placementMethods = {
43
43
  return this.typeOf(d.name);
44
44
  return ts.isParameter(d) ? this.paramType(d) : this.returnTypeOf(d);
45
45
  },
46
- /** A `nullishRead` value as its `JSNullish<T>`. */
47
- nullishCode(e) {
48
- if (!ts.isCallExpression(e) && !ts.isPropertyAccessExpression(e))
49
- return this.refName(e);
50
- this.nullishCalls.add(e);
51
- try {
52
- return this.expr(e);
53
- }
54
- finally {
55
- this.nullishCalls.delete(e);
56
- }
57
- },
46
+ /* nullishCode is installed from semantics/lowering-methods.ts */
58
47
  /** `nullableEntry`'s read: `jsNulledEntry` of the Map value `code` reads, `jsNulledElement` of the element, the field by its key, or a static by its written flag. */
59
48
  nulledEntry(read, code) {
60
49
  if (read.kind === 'static') {
@@ -128,19 +128,7 @@ export const statementsMethods = {
128
128
  });
129
129
  return forward;
130
130
  },
131
- block(b, base) {
132
- if (base === undefined)
133
- base = this.indent;
134
- const saved = this.indent;
135
- this.indent = base + ' ';
136
- try {
137
- const body = this.statements(ts.isBlock(b) ? [...b.statements] : [b]);
138
- return `{\n${body.join('\n')}\n${base}}`;
139
- }
140
- finally {
141
- this.indent = saved;
142
- }
143
- },
131
+ /* block is installed from semantics/lowering-methods.ts */
144
132
  stmt(s) {
145
133
  let code;
146
134
  const at = this.translating;
@@ -40,6 +40,8 @@ export class Translator {
40
40
  spelling = [];
41
41
  /** Variables initialized from an element read (`const r = xs[i]`): nullable, unwrapped where they are used. */
42
42
  undefinedVars = new Map();
43
+ /** Function-local `let s: string` variables only mutated via `+=` in a loop: lowered to `StringBuilder`. */
44
+ stringBuilders = new Set();
43
45
  /** A binding Kotlin holds as nullable though TypeScript types it present: reads take it as the undefined it may be. */
44
46
  bindsOptional(name, type) {
45
47
  const sym = this.checker.getSymbolAtLocation(name);
@@ -311,16 +313,6 @@ export class Translator {
311
313
  taken.set(prefix, n);
312
314
  return this.marks.pureCode(/^__[a-z]$/.test(prefix) ? `${prefix}_${n}` : `${prefix}${n}`);
313
315
  }
314
- nested(body) {
315
- const saved = this.indent;
316
- this.indent += ' ';
317
- try {
318
- return body();
319
- }
320
- finally {
321
- this.indent = saved;
322
- }
323
- }
324
316
  /** A constructor's `return`, inside the labeled block its `init` runs: Kotlin's `init` takes no `return`. */
325
317
  returnLabel = null;
326
318
  /** `return`, or in a lambda `return@` its label. */
@@ -98,7 +98,7 @@ export const typeTestsMethods = {
98
98
  const x = ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses);
99
99
  if (this.lenientApp && ts.isIdentifier(x) && this.declaredTypeOf(x) === optionalType(t))
100
100
  return true;
101
- if (ts.isPropertyAccessExpression(x) && this.optionalMember(x))
101
+ if (ts.isPropertyAccessExpression(x) && this.isLenientOptionalMember(x))
102
102
  return true;
103
103
  if (this.lenientMissingMember(x))
104
104
  return true;
@@ -5,7 +5,7 @@ import { BUFFER_TYPES, WEB_DICTIONARIES, webClassName } from "../semantics/globa
5
5
  import { SPELLING, spell, destructuringSource, functionTypeParts, kotlinString, nullishType, optionalElementsType, optionalType, presentConst, RT } from "./syntax.js";
6
6
  import { ambientBase, evolvingArrayRead, evolvingArrayType, isAmbientClass, isRegExpProtocol, memberOwner, namesOwnTypeParameter, tokenClassBase, isArguments } from "../semantics/lang.js";
7
7
  import { nullishSignalType } from "../semantics/signals.js";
8
- import { hasModifier, isLibDeclaration, thisNodes, isWriteTarget, implementationOf, takesOwnThis } from "../semantics/ast.js";
8
+ import { hasModifier, isLibDeclaration, isWriteTarget, implementationOf, takesOwnThis } from "../semantics/ast.js";
9
9
  import { isCoreDeclaration } from "../program/core-facts.js";
10
10
  import { coreTypeKind, eventDataTypeLiteral, hasMappedIntersection, isJsDocConstructorFunction, isKit, isLibObjectType, isNamed, isUntyped, libraryNativeType, libraryType, mappedOrErasedType, nonNullableInner, nonOptionalSpelling, parseNativeType, spelledType, valueModuleKind } from "../semantics/types.js";
11
11
  import { isStatic } from "../semantics/throws.js";
@@ -642,22 +642,5 @@ export const typesMethods = {
642
642
  const site = this.typeOf(e);
643
643
  return this.returnTypeOf(decl) === optionalType(site) && site !== optionalType(site) && !this.nullTolerant(e);
644
644
  },
645
- /** Runs `body` with `this` in `fn` (and in the arrow functions inside it) read as `name`. */
646
- withThis(fn, name, untyped, body) {
647
- const nodes = thisNodes(fn);
648
- for (const n of nodes) {
649
- this.subst.set(n, name);
650
- if (untyped)
651
- this.untypedThis.add(n);
652
- }
653
- try {
654
- return body();
655
- }
656
- finally {
657
- for (const n of nodes) {
658
- this.subst.delete(n);
659
- this.untypedThis.delete(n);
660
- }
661
- }
662
- },
645
+ /* withThis is installed from semantics/lowering-methods.ts */
663
646
  };
@@ -156,3 +156,12 @@ export function nativeViewOf(checker, type, table = NATIVE_VIEWS) {
156
156
  };
157
157
  return visit(checker.getNonNullableType(type));
158
158
  }
159
+ /** A core member read through a class of the app or a plugin that extends a core class (`this.isPassThroughParentEnabled` in a GridLayout subclass). */
160
+ export function inheritedCoreOwner(target, name, checker, kitRootOf) {
161
+ const decl = checker.getSymbolAtLocation(name)?.valueDeclaration;
162
+ if (!decl || !isCoreDeclaration(decl))
163
+ return null;
164
+ const cls = checker.getNonNullableType(checker.getTypeAtLocation(target)).getSymbol()?.valueDeclaration;
165
+ const root = cls && ts.isClassLike(cls) && !cls.getSourceFile().isDeclarationFile ? kitRootOf(cls) : null;
166
+ return root ? { name: root, isStatic: false } : null;
167
+ }
@@ -37,6 +37,7 @@ export class ProgramFacts {
37
37
  overrideMap = null;
38
38
  familyMap = null;
39
39
  protoKeys = null;
40
+ protoClasses = null;
40
41
  tdzSet = null;
41
42
  ifaceDecls = null;
42
43
  ifaceNamesByTop = new WeakMap();
@@ -452,7 +453,42 @@ export class ProgramFacts {
452
453
  }
453
454
  return (this.protoKeys = { data, accessors });
454
455
  }
455
- /** App-mode module `let`/`const` bindings in an import cycle that may be read before their module initializes. */
456
+ /** Program classes whose `.prototype` object is read or observed via `Object.getPrototypeOf` in app mode. */
457
+ prototypeClasses() {
458
+ if (this.protoClasses)
459
+ return this.protoClasses;
460
+ const out = new Set();
461
+ if (this.scope.library)
462
+ return (this.protoClasses = out);
463
+ let anyGetProto = false;
464
+ const addChain = (cls) => {
465
+ for (let c = cls; c; c = programBase(c, this.checker)) {
466
+ if (ts.isClassDeclaration(c) && !c.getSourceFile().isDeclarationFile)
467
+ out.add(c);
468
+ }
469
+ };
470
+ const visit = (n) => {
471
+ if (ts.isPropertyAccessExpression(n) && n.name.text === 'prototype') {
472
+ const sym = resolveSymbol(n.expression, this.checker);
473
+ if (sym && sym.flags & ts.SymbolFlags.Class && sym.valueDeclaration && ts.isClassLike(sym.valueDeclaration))
474
+ addChain(sym.valueDeclaration);
475
+ }
476
+ else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && ts.isIdentifier(n.expression.expression) && n.expression.expression.text === 'Object' && n.expression.name.text === 'getPrototypeOf') {
477
+ anyGetProto = true;
478
+ }
479
+ ts.forEachChild(n, visit);
480
+ };
481
+ for (const sf of this.files)
482
+ if (!sf.isDeclarationFile)
483
+ visit(sf);
484
+ if (anyGetProto) {
485
+ for (const c of this.classes())
486
+ if (ts.isClassDeclaration(c))
487
+ out.add(c);
488
+ }
489
+ return (this.protoClasses = out);
490
+ }
491
+ /** App-mode module `let`/`const` bindings that may be read before their initializer runs. */
456
492
  tdzBindings() {
457
493
  return (this.tdzSet ??= this.scope.library ? new Set() : cyclicModuleBindings(this.checker, this.files));
458
494
  }
@@ -4,6 +4,7 @@ import { O, U, declarationFile, hasStatic, unionOfObjects, untyped } from "./flo
4
4
  import { LIB_FILE, isTemplateMethod } from "../trust.js";
5
5
  import { implementedInterfaces, literalKey, mergedInterfaceMemberOf } from "../lang.js";
6
6
  import { programBase } from "../classes.js";
7
+ import { hasMappedIntersection } from "../types.js";
7
8
  export const byNameCallsMethods = {
8
9
  /**
9
10
  * Members the framework may call where the program can't see (`FrameworkModel.calledByFramework`), but the template
@@ -119,11 +120,21 @@ export const byNameCallsMethods = {
119
120
  }
120
121
  }
121
122
  };
123
+ const erasedUntyped = (t) => {
124
+ if (untyped(t))
125
+ return true;
126
+ const n = c.getNonNullableType(t);
127
+ return untyped(n) || (n.isIntersection() && hasMappedIntersection(n));
128
+ };
122
129
  const open = (slots) => slots.filter((s) => {
123
130
  const r = this.find(s);
124
131
  // A part's type is the value's own (an array literal's elements), not the type its holder declares.
125
- return !!r.type && (untyped(r.type) || (!!r.decl && unionOfObjects(r.type))) && !(r.decl && LIB_FILE.test(r.decl.getSourceFile().fileName));
132
+ return !!r.type && (erasedUntyped(r.type) || (!!r.decl && unionOfObjects(r.type))) && !(r.decl && LIB_FILE.test(r.decl.getSourceFile().fileName));
126
133
  });
134
+ // A class implementing a mapped-type intersection erased to Any? (`implements Ds3ControllerAsync`) is called dynamically by name.
135
+ for (const cls of this.classes)
136
+ if (implementedInterfaces(c, cls).some((i) => erasedUntyped(c.getTypeAtLocation(i))))
137
+ found.add(cls);
127
138
  // Placed by generated code, or only into `bindingContext`s and the generated code's own slots.
128
139
  const byKeys = (x, slots) => !!keyedFile && (keyedFile(x.getSourceFile()) || (!this.heldUntyped.has(x) && slots.every((s) => keyedSlot(s.decl))));
129
140
  for (const [x, slots] of this.placed) {
@@ -134,7 +145,7 @@ export const byNameCallsMethods = {
134
145
  for (const x of this.placedUntyped)
135
146
  classOf(x, byKeys(x, open(this.placed.get(x) ?? [])));
136
147
  const visit = (n) => {
137
- if ((ts.isAsExpression(n) || ts.isTypeAssertionExpression(n)) && untyped(c.getTypeAtLocation(n)))
148
+ if ((ts.isAsExpression(n) || ts.isTypeAssertionExpression(n)) && erasedUntyped(c.getTypeAtLocation(n)))
138
149
  classOf(n.expression);
139
150
  if (ts.isElementAccessExpression(n)) {
140
151
  const key = ts.skipOuterExpressions(n.argumentExpression);
@@ -325,7 +336,10 @@ export const byNameCallsMethods = {
325
336
  for (const raw of rawTypes) {
326
337
  const wt = c.getNonNullableType(raw);
327
338
  const wanted = wt.getSymbol();
328
- if (!wanted || !(wanted.flags & (ts.SymbolFlags.TypeLiteral | ts.SymbolFlags.Interface)) || wanted.flags & ts.SymbolFlags.Class || wt.getCallSignatures().length || wt.getConstructSignatures().length || !wt.getProperties().length)
339
+ const intersection = wt.isIntersection() && !wt.types.some((u) => (u.getSymbol()?.flags ?? 0) & ts.SymbolFlags.Class);
340
+ if (!intersection && (!wanted || !(wanted.flags & (ts.SymbolFlags.TypeLiteral | ts.SymbolFlags.Interface)) || wanted.flags & ts.SymbolFlags.Class))
341
+ continue;
342
+ if (wt.getCallSignatures().length || wt.getConstructSignatures().length || !wt.getProperties().length)
329
343
  continue;
330
344
  for (const part of t.isUnion() ? t.types : [t]) {
331
345
  const cls = part.getSymbol()?.declarations?.find((d) => ts.isClassLike(d) && !declarationFile(d));
@@ -334,7 +348,7 @@ export const byNameCallsMethods = {
334
348
  this.viewedStatic.add(b);
335
349
  continue;
336
350
  }
337
- if (!cls || names(cls, wanted))
351
+ if (!cls || (wanted && names(cls, wanted)))
338
352
  continue;
339
353
  const keys = wt.getProperties().map((p) => p.name);
340
354
  for (let b = cls; b; b = programBase(b, c)) {
@@ -1,6 +1,7 @@
1
1
  import ts from 'typescript';
2
- import { isSymbolAsyncIterator, isSymbolIterator } from "./ast.js";
2
+ import { isLibDeclaration, isSymbolAsyncIterator, isSymbolIterator } from "./ast.js";
3
3
  import { SHIM_GLOBAL_OBJECT_VARS } from "./globals.js";
4
+ import { implementedInterfaces } from "./lang/members.js";
4
5
  export { evolvingArrayRead, evolvingArrayType, evolvingElementContext, spreadOperand, openSpreadType, intersectionAliasMembers, iterationThrows, iteratedType, iteratesCheckedResult } from "./lang/arrays.js";
5
6
  export { unsafeReceiver, uncheckedMatch, leadingNeverRead, redeclaredBeside, thisArgCall, withoutThisArg, thisArgBound, takesReceiver, ignoresThisArg } from "./lang/this-args.js";
6
7
  export { isAmbientClass, ambientBase, ambientAddedMemberOf, implementedInterfaces, runtimeTypeName, mergedInterfaceMemberOf, augmentedPropertyRead, optionalBodilessMethod, undeclaredMemberOf, classesHeldUntyped, hasStatic, admitsUndefined, assertedOperand, undefinedLiteral, onlyUndefined, resultsAreUndefinedElements, implementedInterfaceDeclarations, accessedDeclaration, memberOwner, namesOwnTypeParameter } from "./lang/members.js";
@@ -246,3 +247,37 @@ export function substitutedExpr(subst, e, branchingOnly = false) {
246
247
  return null;
247
248
  return { bare, code };
248
249
  }
250
+ /** Member names of declared TypeScript interfaces left out of a class's native conformances, so dynamic views (`fromJS` / `init(jsObject:)`) can read them by name. */
251
+ export function droppedProtocolMemberNames(checker, cls, protocols, implemented, ifaceName, skipped) {
252
+ const out = new Set();
253
+ for (const i of implementedInterfaces(checker, cls)) {
254
+ const t = checker.getTypeAtLocation(i);
255
+ if (!isEmittedInterface(t) || isLibDeclaration(t.getSymbol()?.declarations?.[0]))
256
+ continue;
257
+ const name = ifaceName(i);
258
+ if (!protocols.has(name) || implemented.includes(name) || skipped(i, t, name))
259
+ continue;
260
+ for (const p of t.getProperties())
261
+ out.add(p.name);
262
+ }
263
+ return out;
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
+ }
@@ -0,0 +1,90 @@
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
+ }
@@ -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,114 @@ 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
+ },
98
210
  };
@@ -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 });
@@ -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 },