@nstudio/nativescript-compiler 9.2.0-alpha.11 → 9.2.0-alpha.13

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 (70) hide show
  1. package/dist/cli/runtime.cjs +7 -1
  2. package/dist/css/css.js +30 -6
  3. package/dist/driver/compile.js +1 -0
  4. package/dist/driver/paths.js +7 -0
  5. package/dist/kotlin/access.js +1 -1
  6. package/dist/kotlin/arguments.js +1 -20
  7. package/dist/kotlin/conversion.js +17 -5
  8. package/dist/kotlin/expressions.js +8 -3
  9. package/dist/kotlin/literals.js +7 -9
  10. package/dist/kotlin/native/calls.js +84 -3
  11. package/dist/kotlin/operators.js +0 -12
  12. package/dist/kotlin/overrides.js +7 -5
  13. package/dist/kotlin/placement.js +3 -1
  14. package/dist/kotlin/statements.js +1 -16
  15. package/dist/kotlin/static-calls.js +6 -4
  16. package/dist/kotlin/translator.js +31 -17
  17. package/dist/kotlin/type-facts.js +10 -2
  18. package/dist/plugins/native-android.js +173 -4
  19. package/dist/program/program.js +35 -26
  20. package/dist/semantics/facts.js +28 -1
  21. package/dist/semantics/lowering-methods.js +56 -0
  22. package/dist/semantics/shapes.js +21 -1
  23. package/dist/swift/arguments.js +1 -20
  24. package/dist/swift/conversion.js +1 -1
  25. package/dist/swift/from-any.js +2 -2
  26. package/dist/swift/literals.js +4 -4
  27. package/dist/swift/modules.js +1 -1
  28. package/dist/swift/placement.js +2 -3
  29. package/dist/swift/statements.js +1 -16
  30. package/dist/swift/static-calls.js +5 -3
  31. package/dist/swift/translator.js +1 -19
  32. package/dist/targets/android/build.js +5 -3
  33. package/docs/cli/compile-ios.md +4 -0
  34. package/kit-android/generated/kotlin/org/nativescript/kit/application_application.kt +4 -4
  35. package/kit-android/generated/kotlin/org/nativescript/kit/image_source_index.kt +1 -1
  36. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_animation_common.kt +7 -3
  37. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_index.kt +3 -1
  38. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_base_index.kt +2 -4
  39. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_index.kt +5 -6
  40. package/kit-android/generated/kotlin/org/nativescript/kit/ui_dialogs_index.kt +11 -6
  41. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_fragment_transitions.kt +1 -1
  42. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_common.kt +1 -1
  43. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_helper_for_android.kt +7 -5
  44. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_index.kt +6 -3
  45. package/kit-android/generated/kotlin/org/nativescript/kit/ui_gestures_touch_manager.kt +1 -1
  46. package/kit-android/generated/kotlin/org/nativescript/kit/ui_layouts_flexbox_layout_index.kt +1 -1
  47. package/kit-android/generated/kotlin/org/nativescript/kit/ui_search_bar_index.kt +4 -3
  48. package/kit-android/generated/kotlin/org/nativescript/kit/ui_segmented_bar_index.kt +2 -2
  49. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +1 -3
  50. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_index.kt +1 -1
  51. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_fade_transition.kt +1 -1
  52. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_flip_transition.kt +8 -8
  53. package/kit-android/generated/kotlin/org/nativescript/kit/utils_index.kt +1 -1
  54. package/kit-android/generated/source-lines.json +1 -1
  55. package/kit-android/gradlew.bat +94 -0
  56. package/kit-android/src/main/kotlin/org/nativescript/kit/Signals.kt +15 -2
  57. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +2 -15
  58. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +9 -3
  59. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +11 -7
  60. package/kit-apple/Sources/NativeScriptKit/Core/Object_callback_thisArg_once.swift +1 -1
  61. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_index_section_view_ios_android.swift +7 -5
  62. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_oldIndex_newIndex.swift +4 -2
  63. package/kit-apple/Sources/NativeScriptKit/Core/data.observable.index.swift +3 -3
  64. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +6 -2
  65. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.weak-event-listener.index.swift +3 -3
  66. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.index.ios.swift +2 -2
  67. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +6 -2
  68. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.formatted-string.swift +2 -1
  69. package/kit-apple/Sources/NativeScriptKit/Signals.swift +20 -2
  70. package/package.json +2 -1
@@ -4,7 +4,7 @@ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync,
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, join, relative, resolve } from 'node:path';
6
6
  import { archiveClasses } from "../kotlin/native/classfiles.js";
7
- import { cacheDir, KIT_ANDROID } from "../driver/paths.js";
7
+ import { cacheDir, gradleWrapper, KIT_ANDROID } from "../driver/paths.js";
8
8
  import { byName, compareText } from "../program/order.js";
9
9
  /** What the plugin libraries are built with: the generated app's (targets/android/build.ts). */
10
10
  const AGP = '8.12.1', KOTLIN = '2.2.20', COMPILE_SDK = 36, KIT_MIN_SDK = 24;
@@ -193,7 +193,8 @@ ${l.include?.libraryBlocks.join('\n\n') ?? ''}
193
193
  });
194
194
  options.say?.(`building the Android code of ${libraries.map((l) => `${l.source.name}@${l.source.version}`).join(', ')}`);
195
195
  try {
196
- execFileSync(join(kit, 'gradlew'), ['-p', root, 'assembleRelease', '-PtempBuild=true', '--quiet'], { stdio: 'inherit' });
196
+ const gw = gradleWrapper(['-p', root, 'assembleRelease', '-PtempBuild=true', '--quiet'], kit);
197
+ execFileSync(gw.command, gw.args, { stdio: 'inherit' });
197
198
  }
198
199
  catch {
199
200
  throw new Error(`the Android code of ${libraries.map((l, i) => `${l.source.name} (:p${i})`).join(', ')} did not build (Gradle's output is above)`);
@@ -408,13 +409,146 @@ export function parseIncludeGradle(text) {
408
409
  }
409
410
  if (blockOf('packagingOptions') || blockOf('packaging')) {
410
411
  i++;
412
+ const addPackagingItem = (p) => {
413
+ if (is(p, 'id', 'exclude') || is(p, 'id', 'pickFirst')) {
414
+ const list = p.text === 'exclude' ? out.packaging.excludes : out.packaging.pickFirsts;
415
+ i++;
416
+ list.push(stringArgument());
417
+ return;
418
+ }
419
+ if (is(p, 'id', 'excludes') || is(p, 'id', 'pickFirsts')) {
420
+ const list = p.text === 'excludes' ? out.packaging.excludes : out.packaging.pickFirsts;
421
+ i++;
422
+ if (is(peek(), 'punct', '+') && is(peek(1), 'punct', '=')) {
423
+ i += 2;
424
+ list.push(stringArgument());
425
+ return;
426
+ }
427
+ if (is(peek(), 'punct', '.') && is(peek(1), 'id', 'add')) {
428
+ i += 2;
429
+ list.push(stringArgument());
430
+ return;
431
+ }
432
+ }
433
+ unsupported(p);
434
+ };
411
435
  statements((p) => {
412
- const list = is(p, 'id', 'exclude') ? out.packaging.excludes : is(p, 'id', 'pickFirst') ? out.packaging.pickFirsts : unsupported(p);
436
+ if (blockOf('resources') || blockOf('jniLibs')) {
437
+ i++;
438
+ statements(addPackagingItem);
439
+ return;
440
+ }
441
+ addPackagingItem(p);
442
+ });
443
+ return;
444
+ }
445
+ if (blockOf('compileOptions')) {
446
+ i++;
447
+ statements((c) => {
448
+ if (!is(c, 'id', 'sourceCompatibility') && !is(c, 'id', 'targetCompatibility') && !is(c, 'id', 'encoding'))
449
+ unsupported(c);
450
+ i++;
451
+ if (is(peek(), 'punct', '='))
452
+ i++;
453
+ if (is(peek(), 'str') || is(peek(), 'num')) {
454
+ i++;
455
+ return;
456
+ }
457
+ // `JavaVersion.VERSION_1_8` or `JavaVersion.toVersion(...)`.
458
+ expect('id');
459
+ while (is(peek(), 'punct', '.')) {
460
+ i++;
461
+ expect('id');
462
+ }
463
+ if (is(peek(), 'punct', '(')) {
464
+ i++;
465
+ while (!is(peek(), 'punct', ')') && !is(peek(), 'end'))
466
+ i++;
467
+ expect('punct', ')');
468
+ }
469
+ });
470
+ return;
471
+ }
472
+ if (blockOf('kotlinOptions')) {
473
+ i++;
474
+ statements((k) => {
475
+ if (!is(k, 'id', 'jvmTarget') && !is(k, 'id', 'freeCompilerArgs'))
476
+ unsupported(k);
477
+ i++;
478
+ if (is(peek(), 'punct', '=') || (is(peek(), 'punct', '+') && is(peek(1), 'punct', '='))) {
479
+ i += is(peek(), 'punct', '+') ? 2 : 1;
480
+ }
481
+ if (is(peek(), 'punct', '[')) {
482
+ i++;
483
+ while (!is(peek(), 'punct', ']') && !is(peek(), 'end'))
484
+ i++;
485
+ expect('punct', ']');
486
+ return;
487
+ }
488
+ if (is(peek(), 'str') || is(peek(), 'num')) {
489
+ i++;
490
+ return;
491
+ }
492
+ unsupported(peek());
493
+ });
494
+ return;
495
+ }
496
+ if (blockOf('buildFeatures')) {
497
+ i++;
498
+ statements((b) => {
499
+ if (!is(b, 'id') || !['viewBinding', 'buildConfig', 'dataBinding', 'compose', 'aidl', 'resValues'].includes(b.text))
500
+ unsupported(b);
501
+ i++;
502
+ if (is(peek(), 'punct', '='))
503
+ i++;
504
+ if (!is(peek(), 'id', 'true') && !is(peek(), 'id', 'false'))
505
+ unsupported(peek());
506
+ i++;
507
+ });
508
+ return;
509
+ }
510
+ if (blockOf('aaptOptions') || blockOf('androidResources')) {
511
+ i++;
512
+ statements((a) => {
513
+ if (!is(a, 'id', 'noCompress'))
514
+ unsupported(a);
413
515
  i++;
414
- list.push(stringArgument());
516
+ if (is(peek(), 'punct', '='))
517
+ i++;
518
+ if (is(peek(), 'punct', '[')) {
519
+ i++;
520
+ while (!is(peek(), 'punct', ']') && !is(peek(), 'end'))
521
+ i++;
522
+ expect('punct', ']');
523
+ return;
524
+ }
525
+ stringArgument();
526
+ while (is(peek(), 'punct', ',')) {
527
+ i++;
528
+ stringArgument();
529
+ }
415
530
  });
416
531
  return;
417
532
  }
533
+ if (is(s, 'id', 'flavorDimensions')) {
534
+ i++;
535
+ stringArgument();
536
+ while (is(peek(), 'punct', ',')) {
537
+ i++;
538
+ stringArgument();
539
+ }
540
+ return;
541
+ }
542
+ if (is(s, 'id', 'compileSdk') || is(s, 'id', 'compileSdkVersion')) {
543
+ i++;
544
+ if (is(peek(), 'punct', '='))
545
+ i++;
546
+ if (is(peek(), 'num') || is(peek(), 'str')) {
547
+ i++;
548
+ return;
549
+ }
550
+ unsupported(peek());
551
+ }
418
552
  if (!is(s, 'id', 'defaultConfig'))
419
553
  unsupported(s);
420
554
  i++;
@@ -427,6 +561,41 @@ export function parseIncludeGradle(text) {
427
561
  expect('id', 'true');
428
562
  return;
429
563
  }
564
+ if (is(d, 'id', 'targetSdkVersion') || is(d, 'id', 'targetSdk') || is(d, 'id', 'compileSdkVersion') || is(d, 'id', 'compileSdk')) {
565
+ i++;
566
+ if (is(peek(), 'punct', '='))
567
+ i++;
568
+ const paren = is(peek(), 'punct', '(');
569
+ if (paren)
570
+ i++;
571
+ expect('num');
572
+ if (paren)
573
+ expect('punct', ')');
574
+ return;
575
+ }
576
+ if (blockOf('vectorDrawables')) {
577
+ i++;
578
+ statements((v) => {
579
+ if (!is(v, 'id', 'useSupportLibrary'))
580
+ unsupported(v);
581
+ i++;
582
+ if (is(peek(), 'punct', '='))
583
+ i++;
584
+ if (!is(peek(), 'id', 'true') && !is(peek(), 'id', 'false'))
585
+ unsupported(peek());
586
+ i++;
587
+ });
588
+ return;
589
+ }
590
+ if (is(d, 'id', 'vectorDrawables') && is(peek(1), 'punct', '.') && is(peek(2), 'id', 'useSupportLibrary')) {
591
+ i += 3;
592
+ if (is(peek(), 'punct', '='))
593
+ i++;
594
+ if (!is(peek(), 'id', 'true') && !is(peek(), 'id', 'false'))
595
+ unsupported(peek());
596
+ i++;
597
+ return;
598
+ }
430
599
  if (!is(d, 'id', 'minSdkVersion') && !is(d, 'id', 'minSdk'))
431
600
  unsupported(d);
432
601
  i++;
@@ -224,8 +224,10 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
224
224
  const notPlugin = (pkg) => NOT_PLUGINS.test(pkg) || build.adapter.isFrameworkPackage(pkg) || build.stubbedPlugins.has(pkg);
225
225
  // A build that compiles packages from their source compiles some packages the framework's adapter otherwise shims.
226
226
  const shims = { ...SHIMS, ...rules.shims, ...(plugins ? {} : rules.fallbackShims) };
227
- const substituted = new Set(Object.values(rules.substitutions ?? {}).map((s) => s.file));
228
- const files = new Map(virtual);
227
+ const normPath = (p) => p.replace(/\\/g, '/');
228
+ const substituted = new Set(Object.values(rules.substitutions ?? {}).map((s) => normPath(s.file)));
229
+ const virtualNorm = new Set([...virtual.keys()].map(normPath));
230
+ const files = new Map([...virtual].map(([k, v]) => [normPath(k), v]));
229
231
  for (const [m, text] of Object.entries(shims))
230
232
  files.set(shimPath(m), text);
231
233
  const hasDom = appIncludesDomLib(roots[0] ?? [...virtual.keys()][0]);
@@ -260,10 +262,13 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
260
262
  // the other platform's types name what code for that platform holds (`signal<android.view.View | null>`).
261
263
  const pluginFiles = new Set();
262
264
  const extraRoots = new Set();
263
- const isSource = (name) => !name.startsWith('/__shims__/') && !name.endsWith('.d.ts') && (build.adapter.isRuntimeSource(name) || !name.includes('/node_modules/'));
264
- const isApp = (name) => isSource(name) && !pluginFiles.has(name);
265
+ const isSource = (name) => {
266
+ const n = normPath(name);
267
+ return !n.startsWith('/__shims__/') && !n.endsWith('.d.ts') && (build.adapter.isRuntimeSource(n) || !n.includes('/node_modules/'));
268
+ };
269
+ const isApp = (name) => isSource(name) && !pluginFiles.has(normPath(name));
265
270
  // The app's declarations are read for the native APIs they declare: the frameworks' own typings they reference would replace the shims.
266
- const appTypings = new Set(declarations);
271
+ const appTypings = new Set(declarations.map(normPath));
267
272
  const nativeReferences = (text, file) => text.replace(/^\/\/\/\s*<reference\s+(path|types)="([^"]*)"\s*\/>.*$/gm, (line, kind, ref) => {
268
273
  const target = resolve(dirname(file), ref);
269
274
  const pkg = /[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(target)?.[1].replace(/\\/g, '/');
@@ -272,17 +277,18 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
272
277
  // TypeScript loads a file's `/// <reference path>` sources (a package's index referencing its operators barrel) before resolving
273
278
  // the file's imports, so a plugin's referenced source is claimed here or its imports resolve as the app's.
274
279
  const declaredExports = (name, code) => {
275
- if (!pluginFiles.has(name))
280
+ if (!pluginFiles.has(normPath(name)))
276
281
  return code;
277
282
  for (const [, ref] of code.matchAll(/^\/\/\/\s*<reference\s+path="([^"]*\.tsx?)"\s*\/>/gm))
278
283
  if (!ref.endsWith('.d.ts'))
279
- pluginFiles.add(resolve(dirname(name), ref));
284
+ pluginFiles.add(normPath(resolve(dirname(name), ref)));
280
285
  return pluginDeclaredExports(code, name, platform);
281
286
  };
282
- const appRoot = plugins?.options?.app ? resolve(plugins.options.app) : null;
283
- const rootSet = new Set(roots);
287
+ const appRoot = plugins?.options?.app ? normPath(resolve(plugins.options.app)) : null;
288
+ const rootSet = new Set(roots.map(normPath));
284
289
  host.getSourceFile = (name, version, onError) => {
285
- const text = files.get(name) ?? (isSource(name) && existsSync(name) ? readFileSync(name, 'utf8') : appTypings.has(name) ? nativeReferences(readFileSync(name, 'utf8'), name) : undefined);
290
+ const key = normPath(name);
291
+ const text = files.get(key) ?? (isSource(key) && existsSync(name) ? readFileSync(name, 'utf8') : appTypings.has(key) ? nativeReferences(readFileSync(name, 'utf8'), name) : undefined);
286
292
  if (text === undefined) {
287
293
  // A package's own TypeScript (or pure-JS ESM) source.
288
294
  if (!/\.(tsx?|m?js)$/.test(name) || name.endsWith('.d.ts') || !existsSync(name))
@@ -294,15 +300,15 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
294
300
  }
295
301
  return ts.createSourceFile(name, desugarClassMixins(desugarConstructorFactories(declaredExports(name, raw), name), name), version, true);
296
302
  }
297
- const transformed = !name.startsWith('/__shims__/') && !name.startsWith('/__raw__/') && !name.startsWith('/__vite__/') && !name.endsWith('.d.ts') ? vitePlugins.transform(text, name) : text;
298
- const expanded = !name.startsWith('/__shims__/') && !name.endsWith('.d.ts') ? desugarDefaultExport(expandImportMetaGlob(transformed, name, appRoot), name) : transformed;
299
- const code = /\.tsx?$/.test(name) && !name.endsWith('.d.ts') ? desugarClassMixins(desugarConstructorFactories(declaredExports(name, expanded), name), name) : expanded;
300
- return ts.createSourceFile(name, isSource(name) ? foldPlatform(code, name, platform, modules, build.defines) : code, version, true);
303
+ const transformed = !key.startsWith('/__shims__/') && !key.startsWith('/__raw__/') && !key.startsWith('/__vite__/') && !key.endsWith('.d.ts') ? vitePlugins.transform(text, name) : text;
304
+ const expanded = !key.startsWith('/__shims__/') && !key.endsWith('.d.ts') ? desugarDefaultExport(expandImportMetaGlob(transformed, name, appRoot), name) : transformed;
305
+ const code = /\.tsx?$/.test(key) && !key.endsWith('.d.ts') ? desugarClassMixins(desugarConstructorFactories(declaredExports(name, expanded), name), name) : expanded;
306
+ return ts.createSourceFile(name, isSource(key) ? foldPlatform(code, name, platform, modules, build.defines) : code, version, true);
301
307
  };
302
308
  const fileExists = host.fileExists.bind(host);
303
- host.fileExists = (name) => files.has(name) || fileExists(name);
309
+ host.fileExists = (name) => files.has(normPath(name)) || fileExists(name);
304
310
  const readFile = host.readFile.bind(host);
305
- host.readFile = (name) => files.get(name) ?? readFile(name);
311
+ host.readFile = (name) => files.get(normPath(name)) ?? readFile(name);
306
312
  const resolutions = new Map();
307
313
  // A plugin's augmentations of other packages (`declare module '@nativescript/firebase-core'`), which its source keeps in
308
314
  // the declarations beside it (`index.d.ts`), apply as its published typings apply them.
@@ -382,8 +388,9 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
382
388
  const m = aliasTarget ?? lit.text;
383
389
  const substitution = rules.substitutions && Object.hasOwn(rules.substitutions, m) && !replacements[m] ? rules.substitutions[m] : undefined;
384
390
  if (substitution && (plugins || !substitution.sourcesOnly)) {
385
- pluginFiles.add(substitution.file);
386
- return { resolvedModule: { resolvedFileName: substitution.file, extension: ts.Extension.Ts } };
391
+ const subFile = normPath(substitution.file);
392
+ pluginFiles.add(subFile);
393
+ return { resolvedModule: { resolvedFileName: subFile, extension: ts.Extension.Ts } };
387
394
  }
388
395
  if (substitution?.otherwise)
389
396
  return { resolvedModule: { resolvedFileName: shimPath(substitution.otherwise), extension: ts.Extension.Dts } };
@@ -391,33 +398,35 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
391
398
  return { resolvedModule: { resolvedFileName: shimPath(m), extension: ts.Extension.Dts } };
392
399
  const stub = !m.startsWith('.') && !isAbsolute(m) ? build.pluginStubModules.get(packageOf(m)) : undefined;
393
400
  if (stub) {
394
- pluginFiles.add(stub);
395
- return { resolvedModule: { resolvedFileName: stub, extension: ts.Extension.Ts } };
401
+ const stubFile = normPath(stub);
402
+ pluginFiles.add(stubFile);
403
+ return { resolvedModule: { resolvedFileName: stubFile, extension: ts.Extension.Ts } };
396
404
  }
397
405
  // The build's own glue imports app modules by absolute path (`__elements.release.ts`).
398
406
  if (m.startsWith('.') || (isAbsolute(m) && !m.startsWith('/__shims__/'))) {
399
- const base = resolve(dirname(containing), m);
407
+ const base = normPath(resolve(dirname(containing), m));
400
408
  const stem = base.replace(/\.m?js$/, '');
409
+ const containingNorm = normPath(containing);
401
410
  // A platform's own file first, as NativeScript's bundler resolves `./x` to `x.ios.ts`.
402
411
  // A platform file importing its own module's name (`import type { HingeListener } from './hinge-tracker'` in
403
412
  // hinge-tracker.ios.ts) means the module's declarations: `x.d.ts`, else the platforms' shared `x.ts`.
404
413
  const typeOnly = (ts.isImportDeclaration(lit.parent) && !!lit.parent.importClause?.isTypeOnly) || (ts.isExportDeclaration(lit.parent) && lit.parent.isTypeOnly);
405
414
  // A type-only import is TypeScript's, which reads `x.d.ts` beside the platforms' files; only the bundler picks `x.ios.ts`.
406
- const own = containing === `${stem}.${platform}.ts` || (typeOnly && existsSync(stem + '.d.ts'));
415
+ const own = containingNorm === `${stem}.${platform}.ts` || (typeOnly && existsSync(stem + '.d.ts'));
407
416
  const direct = /\.(tsx?|d\.ts)$/.test(base) ? [base] : [];
408
- const jsFallback = pluginFiles.has(containing) ? [...(/\.m?js$/.test(base) ? [base] : []), stem + '.js', stem + '.mjs', stem + '/index.js', stem + '/index.mjs'] : [];
417
+ const jsFallback = pluginFiles.has(containingNorm) ? [...(/\.m?js$/.test(base) ? [base] : []), stem + '.js', stem + '.mjs', stem + '/index.js', stem + '/index.mjs'] : [];
409
418
  for (const candidate of own ? [...direct, stem + '.d.ts', stem + '.ts'] : [...direct, `${stem}.${platform}.ts`, stem + '.ts', stem + '.tsx', `${stem}/index.${platform}.ts`, stem + '/index.ts', ...jsFallback]) {
410
419
  if (files.has(candidate) || existsSync(candidate)) {
411
420
  if (candidate.endsWith('.d.ts'))
412
421
  return { resolvedModule: { resolvedFileName: candidate, extension: ts.Extension.Dts } };
413
422
  // A component file replaced by a compiled `.release.ts` virtual file must resolve to the virtual file everywhere so classes with private members stay nominally identical.
414
423
  const released = candidate.endsWith('.ts') && !candidate.endsWith('.release.ts') ? candidate.replace(/\.ts$/, '.release.ts') : undefined;
415
- if (released && virtual.has(released) && containing !== released)
424
+ if (released && virtualNorm.has(released) && containingNorm !== released)
416
425
  return { resolvedModule: { resolvedFileName: released, extension: ts.Extension.Ts } };
417
426
  // A plugin's own modules, a substitution's file, or a monorepo workspace library outside the app folder
418
427
  // (not already compiled as an app/component root) are compiled through closed-world reachability.
419
- const isCompiledRoot = rootSet.has(candidate) || virtual.has(candidate) || virtual.has(candidate.replace(/\.ts$/, '.release.ts'));
420
- if (!isCompiledRoot && (pluginFiles.has(containing) || substituted.has(candidate) || (aliasTarget && appRoot && !candidate.startsWith(appRoot + sep))))
428
+ const isCompiledRoot = rootSet.has(candidate) || virtualNorm.has(candidate) || virtualNorm.has(candidate.replace(/\.ts$/, '.release.ts'));
429
+ if (!isCompiledRoot && (pluginFiles.has(containingNorm) || substituted.has(candidate) || (aliasTarget && appRoot && !candidate.startsWith(appRoot + '/'))))
421
430
  pluginFiles.add(candidate);
422
431
  const extension = candidate.endsWith('.tsx') ? ts.Extension.Tsx : candidate.endsWith('.mjs') ? ts.Extension.Mjs : candidate.endsWith('.js') ? ts.Extension.Js : ts.Extension.Ts;
423
432
  return { resolvedModule: { resolvedFileName: candidate, extension } };
@@ -4,7 +4,7 @@
4
4
  import ts from 'typescript';
5
5
  import { definitelyAssignedFields, isArguments, classesHeldUntyped } from "./lang.js";
6
6
  import { baseMethod, declaringMethod, literalClassOf, programBase, rootMethod, shapesClassOf } from "./classes.js";
7
- import { expandoRootsOf, instanceKeysOf } from "./shapes.js";
7
+ import { expandoRootsOf, instanceKeysOf, isShapeInterfaceDecl } from "./shapes.js";
8
8
  import { hasModifier, resolveSymbol } from "./ast.js";
9
9
  import { isStatic } from "./throws.js";
10
10
  import { assignedMembers } from "./sharing.js";
@@ -38,6 +38,33 @@ export class ProgramFacts {
38
38
  familyMap = null;
39
39
  protoKeys = null;
40
40
  tdzSet = null;
41
+ ifaceDecls = null;
42
+ ifaceNamesByTop = new WeakMap();
43
+ /** All interface / object-shape type alias declarations across the program's source files. */
44
+ interfaceDecls() {
45
+ if (this.ifaceDecls)
46
+ return this.ifaceDecls;
47
+ const out = [];
48
+ const visit = (n) => {
49
+ if (isShapeInterfaceDecl(n))
50
+ out.push(n);
51
+ ts.forEachChild(n, visit);
52
+ };
53
+ for (const f of this.files)
54
+ visit(f);
55
+ return (this.ifaceDecls = out);
56
+ }
57
+ /** Whether `name` is an interface registered in `interfaces` or declared anywhere in `this.files` under `owner`'s top-level naming. */
58
+ hasInterface(owner, interfaces, topName, name) {
59
+ if (interfaces.has(name))
60
+ return true;
61
+ let set = this.ifaceNamesByTop.get(owner);
62
+ if (!set) {
63
+ set = new Set(this.interfaceDecls().map((n) => topName(n, n.name.text)));
64
+ this.ifaceNamesByTop.set(owner, set);
65
+ }
66
+ return set.has(name);
67
+ }
41
68
  checker;
42
69
  files;
43
70
  scope;
@@ -1,3 +1,8 @@
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.
3
+ import ts from 'typescript';
4
+ import { argumentSlot, place, resultSlot, storeSlot } from "./placement.js";
5
+ import { located } from "./refusals.js";
1
6
  export const loweringMethods = {
2
7
  /** Runs `body` inside a lowered async region: its breaks and continues are the region's, not a native loop's. */
3
8
  withAsync(ctx, body) {
@@ -39,4 +44,55 @@ export const loweringMethods = {
39
44
  this.asyncCtx = saved;
40
45
  }
41
46
  },
47
+ /** An expression placed where the backend needs a value of `target`. */
48
+ coerce(e, target) {
49
+ return place(this.placement, e, target);
50
+ },
51
+ /** `e` stored by `at` (a declaration, an object literal's field, an assignment's target) where the backend holds `target`. */
52
+ stored(e, at, target, checks = true) {
53
+ return place(this.placement, e, this.storeSlot(e, target, at, checks));
54
+ },
55
+ storeSlot(e, target, at, checks = true) {
56
+ return storeSlot(this.placement, target, at, e, checks);
57
+ },
58
+ /** The result slot of the function being translated, where `at` (a `return`, an expression body) gives its value. */
59
+ resultSlot(at) {
60
+ return resultSlot(this.asyncCtx ? this.asyncCtx.result : this.returnType, ts.findAncestor(at.parent, ts.isFunctionLike), !!this.asyncCtx);
61
+ },
62
+ /** An argument of `call` with no declared parameter's cell, as `element`: a built-in's (`Math.max`) or one an untyped callee takes. */
63
+ restArgument(call, a, element) {
64
+ return place(this.placement, a, this.restSlot(call, element)(a));
65
+ },
66
+ /** The slot of each value `at` stores as a container's element (`elementStoreOf`), held as `element`. */
67
+ elementSlot(at, element) {
68
+ return (a) => storeSlot(this.placement, element, at, a);
69
+ },
70
+ /** A value `call` stores as an element of its receiver (`push`'s, `add`'s), held as `element`. */
71
+ elementArgument(call, a, element) {
72
+ return place(this.placement, a, this.elementSlot(call, element)(a));
73
+ },
74
+ /** The slot of each argument `call` gives a rest parameter (`decl`), or an untyped callee: one `element` each, placed with no declared parameter's cell. */
75
+ restSlot(call, element, decl) {
76
+ return (a) => {
77
+ const k = call.arguments?.indexOf(a) ?? -1;
78
+ return argumentSlot(this.placement, element, decl, { call, k, a: k < 0 ? undefined : a }, { rest: true });
79
+ };
80
+ },
81
+ /** An error the translation of `n` failed with, at `n` unless it says where already (semantics/refusals.ts). */
82
+ located(e, n) {
83
+ return located(e, n, (at, what, id) => this.error(at, what, id));
84
+ },
85
+ error(n, what, id = 'unhandled') {
86
+ if (!n)
87
+ return this.config.refusals.refusal(`${what} is not supported in a release build yet`, id);
88
+ const sf = n.getSourceFile();
89
+ const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
90
+ return this.config.refusals.refusedAt(sf.fileName, line + 1, character + 1, what, n.getText().slice(0, 80), id);
91
+ },
92
+ /** A declared limit of release builds: refused with why and how to write it instead. */
93
+ limit(n, id, what) {
94
+ const sf = n.getSourceFile();
95
+ const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
96
+ return this.config.refusals.limitAt(sf.fileName, line + 1, character + 1, what, n.getText().slice(0, 80), id);
97
+ },
42
98
  };
@@ -1,5 +1,5 @@
1
1
  import ts from 'typescript';
2
- import { heldOf, isPrimitive, presentOf, spelledType } from "./types.js";
2
+ import { heldOf, isPrimitive, isUntyped, presentOf, spelledType } from "./types.js";
3
3
  import { admitsUndefined, alwaysThrows, containsThis, hasStatic, jsKeyOrder, literalKey, onlyUndefined } from "./lang.js";
4
4
  import { programBase } from "./classes.js";
5
5
  import { assignsClassFields } from "./class-plan.js";
@@ -39,6 +39,18 @@ export function inPlanOrder(plan, fields) {
39
39
  }
40
40
  /** The type holds nil as its value: `T?`, `Any?`. */
41
41
  export const holdsNil = (h) => h === 'optional' || h === 'any';
42
+ /** An interface or object-shape type alias declared in program source (collected upfront for order-independent checks). */
43
+ export const isShapeInterfaceDecl = (n) => !n.getSourceFile().isDeclarationFile && (ts.isInterfaceDeclaration(n) || (ts.isTypeAliasDeclaration(n) && (ts.isTypeLiteralNode(n.type) || ts.isIntersectionTypeNode(n.type))));
44
+ /** Property access inside `Array.isArray(x)` when `x` reads a property off an object shape / interface view. */
45
+ export function shapeArrayGuardAccess(arg, isShape, typeOf) {
46
+ const a0 = arg ? ts.skipParentheses(arg) : undefined;
47
+ if (!a0 || !ts.isPropertyAccessExpression(a0))
48
+ return null;
49
+ const recvType = typeOf(a0.expression);
50
+ if (!isShape(recvType.replace(/[?!]$/, '')))
51
+ return null;
52
+ return { prop: a0, optional: !!a0.questionDotToken || recvType.endsWith('?') };
53
+ }
42
54
  /** The spelling ends in `?`, a function's result's included. */
43
55
  export const spelledOptional = (h) => holdsNil(h) || h === 'optional-result';
44
56
  /** The type holds nil, implicitly unwrapped or not. */
@@ -658,3 +670,11 @@ function runsCode(n, deep = true) {
658
670
  visit(n);
659
671
  return found;
660
672
  }
673
+ /** Whether spreading elements of `from` into an array of `to` requires elementwise mapping (untyped source or distinct structural shapes). */
674
+ export function spreadElementNeedsMap(from, to, isShape, mapUntyped) {
675
+ if (from === to)
676
+ return false;
677
+ if (mapUntyped && isUntyped(spelledType(from)))
678
+ return true;
679
+ return !isUntyped(spelledType(to)) && isShape(to.replace(/\?$/, '')) && isShape(from.replace(/\?$/, ''));
680
+ }
@@ -1,7 +1,7 @@
1
1
  // A call's arguments as Swift: the slot each parameter takes, missing and spread arguments, rest and packed arguments.
2
2
  import ts from 'typescript';
3
3
  import { functionParts, heldType, isOptional, nullishType, optionalType, RT } from "./syntax.js";
4
- import { argumentSlot, place, storeSlot } from "../semantics/placement.js";
4
+ import { argumentSlot, place } from "../semantics/placement.js";
5
5
  import { implementationOf } from "../semantics/ast.js";
6
6
  import { isStatic } from "../semantics/throws.js";
7
7
  import { isUntyped, spelledType } from "../semantics/types.js";
@@ -199,25 +199,6 @@ export const argumentsMethods = {
199
199
  return `, spread: ${this.packed(args, 'JSArray<Any?>', slot)}.storage`;
200
200
  return args.map((a) => `, ${place(this.placement, a, slot(a))}`).join('');
201
201
  },
202
- /** An argument of `call` with no declared parameter's cell, as `element`: a built-in's (`Math.max`) or one an untyped callee takes. */
203
- restArgument(call, a, element) {
204
- return place(this.placement, a, this.restSlot(call, element)(a));
205
- },
206
- /** The slot of each value `at` stores as a container's element (`elementStoreOf`), held as `element`. */
207
- elementSlot(at, element) {
208
- return (a) => storeSlot(this.placement, element, at, a);
209
- },
210
- /** A value `call` stores as an element of its receiver (`push`'s, `add`'s), held as `element`. */
211
- elementArgument(call, a, element) {
212
- return place(this.placement, a, this.elementSlot(call, element)(a));
213
- },
214
- /** The slot of each argument `call` gives a rest parameter (`decl`), or an untyped callee: one `element` each, placed with no declared parameter's cell. */
215
- restSlot(call, element, decl) {
216
- return (a) => {
217
- const k = call.arguments?.indexOf(a) ?? -1;
218
- return argumentSlot(this.placement, element, decl, { call, k, a: k < 0 ? undefined : a }, { rest: true });
219
- };
220
- },
221
202
  /** Arguments (spreads included) as one `JSArray` of `arrayType`; `slot` places each element where they are a call's. */
222
203
  packed(items, arrayType, slot) {
223
204
  const el = arrayType.replace(/^JSArray<(.*)>$/, '$1');
@@ -299,7 +299,7 @@ export const conversionMethods = {
299
299
  if (isUntyped(spelledType(from)))
300
300
  return this.fromAny(code, to);
301
301
  // An event's data read as the object type a handler declares (`({ window }: { window: NativeWindow })`).
302
- if (from === 'EventData' && (this.interfaces.has(to.replace(/\?$/, '')) || !!this.shapes.named(to.replace(/\?$/, ''))))
302
+ if (from === 'EventData' && (this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), to.replace(/\?$/, '')) || !!this.shapes.named(to.replace(/\?$/, ''))))
303
303
  return this.fromAny(code, to);
304
304
  const f = functionParts(unwrapFunction(from, false));
305
305
  const g = functionParts(unwrapFunction(to, false));
@@ -253,12 +253,12 @@ export const fromAnyMethods = {
253
253
  if (whole)
254
254
  return this.unboxFunction(code, whole);
255
255
  const base = type.replace(/\?$/, '');
256
- if (this.protocols.has(base) && this.interfaces.has(base)) {
256
+ if (this.protocols.has(base) && this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), base)) {
257
257
  this.used.add(base);
258
258
  // An interface classes implement: an object conforming to it as it is, any other read by its keys.
259
259
  return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}, { (${RT.jsFlat}($0) as? ${base}) ?? ${base}Object(jsObject: $0) })` : `{ (__o: Any?) -> ${base} in (${RT.jsFlat}(__o) as? ${base}) ?? ${base}Object(jsObject: __o) }(${code})`;
260
260
  }
261
- if (this.interfaces.has(base) || !!this.shapes.named(base) || (!this.library && this.core.viewable(base))) {
261
+ if (this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), base) || !!this.shapes.named(base) || (!this.library && this.core.viewable(base))) {
262
262
  this.used.add(base);
263
263
  // An object of the interface's class already is the object read (a receiver `call` passes); any other is read by its keys.
264
264
  return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}, { (${RT.jsFlat}($0) as? ${base}) ?? ${this.viewOf(base, '$0')} })` : `{ (__o: Any?) -> ${base} in (${RT.jsFlat}(__o) as? ${base}) ?? ${this.viewOf(base, '__o')} }(${code})`;
@@ -3,7 +3,7 @@ import ts from 'typescript';
3
3
  import { functionParts, ident, identPath, initOrder, isNullish, isOptional, label, optionalType, splitTopLevel, swiftString, withoutThenables, spell, RT } from "./syntax.js";
4
4
  import { assertedOperand, evolvingElementContext, intersectionAliasMembers, isTypeParameterType, literalKey, openSpreadType, spreadOperand, unquoted } from "../semantics/lang.js";
5
5
  import { place } from "../semantics/placement.js";
6
- import { holdsNil, literalNotes, signatureField, shapePlanOfLiteral, spelledOptional, resultShapeNamed } from "../semantics/shapes.js";
6
+ import { holdsNil, literalNotes, signatureField, shapePlanOfLiteral, spelledOptional, spreadElementNeedsMap, resultShapeNamed } from "../semantics/shapes.js";
7
7
  import { isCoreDeclaration } from "../program/core-facts.js";
8
8
  import { hasModifier, thisNodes, tupleSpreadTypes, withoutDefault } from "../semantics/ast.js";
9
9
  import { programSymbolKey } from "../program/stable-names.js";
@@ -88,9 +88,9 @@ export const literalsMethods = {
88
88
  parts.push(`[${run.join(', ')}]`);
89
89
  run = [];
90
90
  }
91
- // The spread's elements as this array's (`[name, ...untyped]` into a `string[]`).
92
- const from = this.elementTypeOf(x.expression);
93
- parts.push(from !== el && isUntyped(spelledType(from)) ? `Array(${this.iterable(x.expression)}).map { ${this.fromAny('$0', el)} }` : `Array(${this.iterable(x.expression)})`);
91
+ // The spread's elements as this array's (`[name, ...untyped]` into a `string[]`, or `[...derived]` into a base shape array).
92
+ const needsMap = spreadElementNeedsMap(this.elementTypeOf(x.expression), el, (n) => this.isObjectShape(n), true);
93
+ parts.push(needsMap ? `Array(${this.iterable(x.expression)}).map { ${this.fromAny('$0', el)} }` : `Array(${this.iterable(x.expression)})`);
94
94
  }
95
95
  else if (ts.isOmittedExpression(x))
96
96
  throw this.error(x, 'an array hole', 'array-hole');
@@ -581,7 +581,7 @@ export const modulesMethods = {
581
581
  return { shape: (n) => this.isObjectShape(n), extends: (a, b) => !!this.classNamed(a) && this.sourceExtends(a, b) };
582
582
  },
583
583
  isObjectShape(name) {
584
- return (this.interfaces.has(name) && !this.protocols.has(name)) || !!this.shapes.named(name) || (!this.library && this.core.viewable(name));
584
+ return (this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), name) && !this.protocols.has(name)) || !!this.shapes.named(name) || (!this.library && this.core.viewable(name));
585
585
  },
586
586
  /** An interface's members with those of the interfaces it extends (`StageFold extends Rect`), its own first. */
587
587
  interfaceMembers(decl) {
@@ -178,7 +178,7 @@ export const placementMethods = {
178
178
  if (!shape) {
179
179
  // An interface's object class, whose fields are its property signatures.
180
180
  const d = this.checker.getSymbolAtLocation(e.name)?.valueDeclaration;
181
- if (!d || !ts.isPropertySignature(d) || !ts.isInterfaceDeclaration(d.parent) || d.parent.name.text !== held || !this.interfaces.has(held) || this.protocols.has(held))
181
+ if (!d || !ts.isPropertySignature(d) || !ts.isInterfaceDeclaration(d.parent) || d.parent.name.text !== held || !this.facts.hasInterface(this, this.interfaces, (x, s) => this.topName(x, s), held) || this.protocols.has(held))
182
182
  return null;
183
183
  const t = this.typeOf(d);
184
184
  return (d.questionToken || holdsNil(heldOf(spelledType(t)))) && heldOf(spelledType(t)) !== 'any' ? e.name.text : null;
@@ -703,8 +703,7 @@ export const placementMethods = {
703
703
  if (/^\(.*\)$/.test(source) && !functionParts(source) && /^JSArray<.*>[?!]?$/.test(target))
704
704
  return this.convert(this.expr(e), source, target);
705
705
  // An array literal is made of the slot's element type already.
706
- const literal = ts.isArrayLiteralExpression(bare) && !bare.elements.some(ts.isSpreadElement);
707
- if (literal && /^JSArray<.+>[?!]?$/.test(source) && /^JSArray<.+>[?!]?$/.test(target) && ['elements', 'view'].includes(structural(parseNativeType(source), parseNativeType(target), this.structuralFacts())?.step ?? ''))
706
+ if (ts.isArrayLiteralExpression(bare) && /^JSArray<.+>[?!]?$/.test(source) && /^JSArray<.+>[?!]?$/.test(target) && ['elements', 'view'].includes(structural(parseNativeType(source), parseNativeType(target), this.structuralFacts())?.step ?? ''))
708
707
  return this.expr(e);
709
708
  if (/^JSArray<\w+>[?!]?$/.test(source) && /^JSArray<\w+>[?!]?$/.test(target) && source.replace(/[?!]$/, '') !== target.replace(/[?!]$/, ''))
710
709
  return this.convert(this.expr(e), source, target);