peachsim 0.1.730 → 0.1.745

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 (105) hide show
  1. package/cli/bridge-flow-runner.ts +15 -2
  2. package/cli/commands/control.ts +13 -3
  3. package/cli/commands/desktop.ts +1 -0
  4. package/cli/commands/electron.ts +12 -8
  5. package/cli/commands/flow.ts +1 -3
  6. package/cli/commands/install-desktop.ts +105 -66
  7. package/cli/commands/logout.ts +5 -1
  8. package/cli/commands/no-bridge-hint.ts +2 -2
  9. package/cli/commands/swift.ts +26 -9
  10. package/cli/desktop-companion.ts +36 -9
  11. package/cli/drivers/desktop.ts +65 -0
  12. package/cli/drivers/electron.ts +4 -66
  13. package/cli/drivers/index.ts +1 -0
  14. package/cli/drivers/playwright.ts +3 -3
  15. package/cli/drivers/registry.ts +7 -2
  16. package/cli/drivers/types.ts +4 -3
  17. package/cli/maestro-js.ts +10 -0
  18. package/cli/outbound-endpoints.ts +2 -2
  19. package/dist-lib/agent-daemon-client.cjs +1 -1
  20. package/dist-lib/agent-events.cjs +1 -1
  21. package/dist-lib/agent-identity.cjs +1 -1
  22. package/dist-lib/agent-sessions.cjs +1 -1
  23. package/dist-lib/attached-projects.cjs +1 -1
  24. package/dist-lib/auth/shared-session.cjs +39 -9
  25. package/dist-lib/backend-origin.cjs +1 -1
  26. package/dist-lib/beta.cjs +1 -1
  27. package/dist-lib/beta.mjs +1 -1
  28. package/dist-lib/bridge-constants.cjs +1 -1
  29. package/dist-lib/bridge-contract-input.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.mjs +1 -1
  31. package/dist-lib/bridge-contract.cjs +1 -1
  32. package/dist-lib/bridge-contract.mjs +1 -1
  33. package/dist-lib/capture-contract.cjs +13 -19
  34. package/dist-lib/capture-contract.mjs +13 -19
  35. package/dist-lib/cli-constants.cjs +1 -1
  36. package/dist-lib/cloud-contract.cjs +1 -1
  37. package/dist-lib/cloud-contract.mjs +1 -1
  38. package/dist-lib/cloud-test-args.cjs +1 -1
  39. package/dist-lib/cloud-test-args.mjs +1 -1
  40. package/dist-lib/cloud.cjs +1 -1
  41. package/dist-lib/cloud.mjs +1 -1
  42. package/dist-lib/config.cjs +1 -1
  43. package/dist-lib/detox/index.cjs +20 -2
  44. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  45. package/dist-lib/home-paths.cjs +32 -1
  46. package/dist-lib/host/bridge-host.cjs +1616 -532
  47. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  48. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  49. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  50. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  51. package/dist-lib/host/websocket-proxy.cjs +1 -1
  52. package/dist-lib/index.cjs +14 -19
  53. package/dist-lib/jump-to-source-babel.cjs +1 -1
  54. package/dist-lib/jump-to-source-native.cjs +1 -1
  55. package/dist-lib/kotlin-host.cjs +1 -1
  56. package/dist-lib/menu.cjs +1 -1
  57. package/dist-lib/menu.mjs +1 -1
  58. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  59. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  60. package/dist-lib/metro-production-bundle.cjs +1 -1
  61. package/dist-lib/metro-production-bundle.mjs +1 -1
  62. package/dist-lib/metro.cjs +1 -1
  63. package/dist-lib/native-app-identity.cjs +1 -1
  64. package/dist-lib/native-app-identity.mjs +1 -1
  65. package/dist-lib/native-firebase-metadata.cjs +1 -1
  66. package/dist-lib/native-firebase-metadata.mjs +1 -1
  67. package/dist-lib/plist.cjs +1 -1
  68. package/dist-lib/plist.mjs +1 -1
  69. package/dist-lib/profiles.cjs +1 -1
  70. package/dist-lib/public-brand.cjs +1 -1
  71. package/dist-lib/react-native-host-modules.cjs +1 -1
  72. package/dist-lib/react-native-host-modules.mjs +1 -1
  73. package/dist-lib/render-mode.cjs +1 -1
  74. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  75. package/dist-lib/sdk.cjs +2 -1
  76. package/dist-lib/sdk.mjs +2 -1
  77. package/dist-lib/skills.cjs +2306 -1067
  78. package/dist-lib/swift-compile.cjs +317 -60
  79. package/dist-lib/swift-compile.mjs +313 -61
  80. package/dist-lib/swift-package.cjs +146 -9
  81. package/dist-lib/swift-package.mjs +144 -9
  82. package/dist-lib/swift-submit.cjs +2 -2
  83. package/dist-lib/swift-submit.mjs +2 -2
  84. package/dist-lib/swift-toolchain.cjs +1 -1
  85. package/dist-lib/swift.cjs +1 -1
  86. package/dist-lib/vite-swift.cjs +1310 -226
  87. package/dist-lib/vite.cjs +1 -1
  88. package/package.json +1 -1
  89. package/skills/contrast/SKILL.md +1 -1
  90. package/src/auth/shared-session.ts +45 -9
  91. package/src/bridge-constants.ts +7 -7
  92. package/src/capture-contract.ts +18 -33
  93. package/src/desktop-host-delivery.ts +81 -0
  94. package/src/home-paths.ts +30 -0
  95. package/src/host/bridge-host.ts +11 -6
  96. package/src/native-seam-manifest.ts +0 -11
  97. package/src/sim-client.ts +1 -0
  98. package/src/swift-compile.ts +403 -68
  99. package/src/swift-distribution.lock.json +11 -11
  100. package/src/swift-host.ts +316 -43
  101. package/src/swift-package.ts +204 -19
  102. package/src/swift-remote-packages.ts +255 -0
  103. package/src/swift-submit.ts +4 -1
  104. package/src/vite-plugin.ts +19 -8
  105. package/src/xcode-project.ts +527 -0
@@ -1,4 +1,4 @@
1
- import { execFile } from 'node:child_process'
1
+ import { execFile, execFileSync } from 'node:child_process'
2
2
  import { createHash } from 'node:crypto'
3
3
  import {
4
4
  cpSync,
@@ -247,6 +247,9 @@ const OPTIONAL_FRAMEWORK_DEPENDENCIES: Record<string, string[]> = {
247
247
  CryptoKit: [],
248
248
  CommonCrypto: [],
249
249
  CoreText: [],
250
+ Compression: ['PeachCodec'],
251
+ zlib: ['PeachCodec'],
252
+ PeachCodec: [],
250
253
  Security: ['CryptoKit'],
251
254
  TikTokBusinessSDK: [],
252
255
  nSure: [],
@@ -258,6 +261,101 @@ const OPTIONAL_FRAMEWORK_DEPENDENCIES: Record<string, string[]> = {
258
261
  }
259
262
  const OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES))
260
263
 
264
+ // an import may carry attributes (`@_exported`, `@preconcurrency`) and a
265
+ // declaration kind (`import struct Nuke.ImageRequest`).
266
+ const SWIFT_IMPORT =
267
+ /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/
268
+
269
+ /**
270
+ * the modules a source imports, in order. `unconditional` keeps only imports
271
+ * outside every `#if`: a conditional one may compile out (`os(macOS)`,
272
+ * `canImport`), so only an unconditional import is certainly required.
273
+ */
274
+ export function swiftImportNames(contents: string, unconditional = false): string[] {
275
+ const names: string[] = []
276
+ let depth = 0
277
+ for (const line of contents.split('\n')) {
278
+ const directive = /^\s*#(if|endif)\b/.exec(line)?.[1]
279
+ if (directive === 'if') depth++
280
+ else if (directive === 'endif') depth = Math.max(0, depth - 1)
281
+ if (unconditional && depth > 0) continue
282
+ const name = SWIFT_IMPORT.exec(line)?.[1]
283
+ if (name) names.push(name)
284
+ }
285
+ return names
286
+ }
287
+
288
+ /**
289
+ * the modules peach itself provides at `moduleRoot`: a distribution lists
290
+ * them, a checkout's manifest declares them as targets.
291
+ */
292
+ export function swiftPeachModules(moduleRoot: string): string[] {
293
+ const distribution = swiftDistributionAt(moduleRoot)
294
+ return distribution
295
+ ? distribution.modules
296
+ : [
297
+ ...readFileSync(path.join(moduleRoot, 'Package.swift'), 'utf8').matchAll(
298
+ /\.(?:target|systemLibrary)\(\s*name:\s*"([^"]+)"/g,
299
+ ),
300
+ ].map((match) => match[1]!)
301
+ }
302
+
303
+ const availableModules = new Map<string, Set<string>>()
304
+
305
+ /**
306
+ * every module a source compiled against `moduleRoot` can import: Peach's own
307
+ * and the wasm SDK's swift modules and top-level clang modules.
308
+ */
309
+ export function swiftAvailableModules(
310
+ moduleRoot: string,
311
+ toolchainBin: string,
312
+ ): Set<string> {
313
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId
314
+ const key = `${moduleRoot}\0${sdk}`
315
+ const cached = availableModules.get(key)
316
+ if (cached) return cached
317
+ const modules = new Set(swiftPeachModules(moduleRoot))
318
+ const configuration = execFileSync(
319
+ path.join(toolchainBin, 'swift'),
320
+ ['sdk', 'configure', '--show-configuration', sdk, 'wasm32-unknown-wasip1'],
321
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
322
+ )
323
+ const resources = /^swiftResourcesPath:\s*(.+)$/m.exec(configuration)?.[1]?.trim()
324
+ if (!resources) throw new Error(`swift sdk ${sdk} reports no swiftResourcesPath`)
325
+ for (const entry of readdirSync(path.join(resources, 'wasi'))) {
326
+ if (entry.endsWith('.swiftmodule'))
327
+ modules.add(entry.slice(0, -'.swiftmodule'.length))
328
+ }
329
+ for (const entry of readdirSync(resources)) {
330
+ const map = path.join(resources, entry, 'module.modulemap')
331
+ if (!existsSync(map)) continue
332
+ for (const match of readFileSync(map, 'utf8').matchAll(/^module\s+([A-Za-z_]\w*)/gm))
333
+ modules.add(match[1]!)
334
+ }
335
+ availableModules.set(key, modules)
336
+ return modules
337
+ }
338
+
339
+ /**
340
+ * the modules the sources import outside any `#if` that nothing available
341
+ * provides, each with the files importing it. the compiler stops at the first
342
+ * missing module; this names all of them at once.
343
+ */
344
+ export function missingSwiftModules(
345
+ files: Record<string, string>,
346
+ available: ReadonlySet<string>,
347
+ ): Map<string, string[]> {
348
+ const missing = new Map<string, string[]>()
349
+ for (const [file, contents] of Object.entries(files)) {
350
+ if (!file.endsWith('.swift') || file === 'Package.swift') continue
351
+ for (const name of new Set(swiftImportNames(contents, true))) {
352
+ if (available.has(name)) continue
353
+ missing.set(name, [...(missing.get(name) ?? []), file])
354
+ }
355
+ }
356
+ return new Map([...missing].sort(([left], [right]) => left.localeCompare(right)))
357
+ }
358
+
261
359
  export function swiftTargetDependencies(
262
360
  files: Record<string, string>,
263
361
  targets: Pick<SwiftPackageTarget, 'name' | 'path'>[],
@@ -279,12 +377,8 @@ export function swiftTargetDependencies(
279
377
  )
280
378
  )
281
379
  continue
282
- // an import may carry attributes (`@_exported`, `@preconcurrency`) and a
283
- // declaration kind (`import struct Nuke.ImageRequest`).
284
- for (const match of contents.matchAll(
285
- /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/gm,
286
- )) {
287
- if (names.has(match[1]) && match[1] !== target.name) deps.add(match[1])
380
+ for (const name of swiftImportNames(contents)) {
381
+ if (names.has(name) && name !== target.name) deps.add(name)
288
382
  }
289
383
  }
290
384
  siblings.set(target.name, [...deps].sort())
@@ -299,24 +393,28 @@ const SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")
299
393
  const importsSpriteKit = (files: Record<string, string>): boolean =>
300
394
  Object.entries(files).some(
301
395
  ([file, contents]) =>
302
- file.endsWith('.swift') &&
303
- /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?SpriteKit\b/m.test(
304
- contents,
305
- ),
396
+ file.endsWith('.swift') && swiftImportNames(contents).includes('SpriteKit'),
306
397
  )
307
398
  // every iOS source sees through Foundation what darwin's Foundation exports:
308
399
  // PeachObjC supplies the ObjectiveC module's selectors, Dispatch Foundation's
309
400
  // Darwin queue exports, and FoundationNetworking (re-exporting PeachFoundation)
310
401
  // URLSession, NotificationCenter, OperationQueue and the CoreFoundation types.
311
- // these modules export only names iOS has; Peach's host plumbing is `package`
312
- // or lives in PeachJSON, which none of them re-exports. scripts/contrast-app-Package.swift and
402
+ // WASILibc is the platform libc the way Darwin's headers are on iOS: its
403
+ // math.h answers the free round Kingfisher's SizeExtensions reaches, and its
404
+ // pthread mutexes are what a Foundation-only source reaches there
405
+ // (SwiftSoup's Mutex). pthread.h is not in the overlay's module: the sdk's
406
+ // wasi-libc.modulemap (swift_static/wasi/wasm32) carries it as the separate
407
+ // top-level module wasi_pthread, which nothing re-exports, so the flags name
408
+ // both. these modules export only names iOS has, WASILibc's wasi-only names
409
+ // aside; Peach's host plumbing is `package` or lives in PeachJSON, which none
410
+ // of them re-exports. scripts/contrast-app-Package.swift and
313
411
  // example/Package.swift carry the same flags.
314
412
  const FOUNDATION_IMPLICIT_FLAGS =
315
- ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"'
413
+ ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking", "-Xfrontend", "-import-module", "-Xfrontend", "WASILibc", "-Xfrontend", "-import-module", "-Xfrontend", "wasi_pthread"'
316
414
  const ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"'
317
415
 
318
416
  /** bump with any change to the emitted multi-target manifest text. */
319
- export const MULTI_MANIFEST_VERSION = 10
417
+ export const MULTI_MANIFEST_VERSION = 11
320
418
 
321
419
  export function swiftArtifactHash(
322
420
  input: SwiftCompileInput,
@@ -324,6 +422,9 @@ export function swiftArtifactHash(
324
422
  moduleRoot: string,
325
423
  ): string {
326
424
  const hash = createHash('sha256')
425
+ // v16: overrides of @objc extension members rename to __peach_ovr_
426
+ // v15: Foundation-only sources see the platform libc (WASILibc, including
427
+ // math round) and its pthread mutexes (wasi_pthread)
327
428
  // v14: AnyObject doubleValue lowers to the typed _objcNumber getter
328
429
  // v13: implicit target resources synthesize Bundle.module
329
430
  // v12: overrides in an extension of a same-file class lift into the class
@@ -334,7 +435,7 @@ export function swiftArtifactHash(
334
435
  // v6: app and scene delegate classes compile final
335
436
  // (v5: a target declaring resources gets SwiftPM's Bundle.module accessor;
336
437
  // v4: sources compile through swiftSourceAsIOS)
337
- hash.update(`swift-compile/v14\n${release}\n`)
438
+ hash.update(`swift-compile/v16\n${release}\n`)
338
439
  if (input.oneModule) hash.update('one-module\n')
339
440
  hash.update(swiftModuleDigest(moduleRoot))
340
441
  for (const file of Object.keys(input.files).sort()) {
@@ -560,12 +661,17 @@ const CLASS_BASE =
560
661
  const FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/
561
662
  // uikit's members are @objc, so an app may override one from an extension;
562
663
  // swift without an objc runtime rejects that. an `override` of an @objc
563
- // member (overridesObjC below) that is a direct member of an extension of a
664
+ // member (overrideKind below) that is a direct member of an extension of a
564
665
  // class declared in the same file is lifted: the extension keeps it as `__peach_ext_<name>` with `override`
565
666
  // blanked, and the class body gains, on its opening brace's line, an
566
667
  // override that forwards to it, so lines keep their numbers and the
567
- // override takes its place in the class as an objc one does. a class in
568
- // another file, a property with a setter or observers, a subscript and a
668
+ // override takes its place in the class as an objc one does. a member the
669
+ // superclass declares in an extension instead of its class body (an @objc
670
+ // one on iOS) cannot keep its name without an objc runtime at all: any
671
+ // same-name member fails, with `override`, @nonobjc or the @ObjC macro's
672
+ // same-named static accessors alike. so the override drops `override` and
673
+ // takes `__peach_ovr_<name>`, keeping its body and lines. a member from
674
+ // another module, a property with a setter or observers, a subscript and a
569
675
  // variadic parameter stay as written and fail to compile as before.
570
676
  // an Apple framework class: an ObjC prefix and a capital
571
677
  const APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/
@@ -609,8 +715,108 @@ function forwardedArguments(parameters: string): string | null {
609
715
  return args.join(', ')
610
716
  }
611
717
 
612
- function liftExtensionOverrides(source: string): string {
718
+ // the offset just past the brace that closes the one at `open`
719
+ function closingBrace(source: string, tokens: number[], open: number): number {
720
+ let depth = 0
721
+ for (const at of tokens) {
722
+ if (at < open) continue
723
+ if (source[at] === '{') depth++
724
+ else if (source[at] === '}' && --depth === 0) return at + 1
725
+ }
726
+ return source.length
727
+ }
728
+
729
+ // every @objc instance member extensions declare, by extended type: the
730
+ // module-wide view one file's lowering cannot see. private, fileprivate,
731
+ // static and class members are never overridable and stay out.
732
+ function scanObjCExtensionMembers(
733
+ source: string,
734
+ tokens: number[],
735
+ records: { type: string; open: number; objcMembers: boolean }[],
736
+ ): Map<string, Set<string>> {
737
+ const masked = swiftCodeMask(source)
738
+ const found = new Map<string, Set<string>>()
739
+ const member = /\b(func|var)\s+([A-Za-z_]\w*)/g
740
+ for (const record of records) {
741
+ const close = closingBrace(source, tokens, record.open)
742
+ const body = masked.slice(record.open, close)
743
+ member.lastIndex = 0
744
+ for (let match = member.exec(body); match; match = member.exec(body)) {
745
+ const at = record.open + match.index + match[0].indexOf(match[1]!)
746
+ let depth = 0
747
+ for (const token of tokens) {
748
+ if (token <= record.open) continue
749
+ if (token >= at) break
750
+ if (source[token] === '{') depth++
751
+ else if (source[token] === '}') depth--
752
+ }
753
+ if (depth > 0) continue
754
+ const head = masked.slice(record.open, at)
755
+ const bound = Math.max(
756
+ head.lastIndexOf(';'),
757
+ head.lastIndexOf('{'),
758
+ head.lastIndexOf('}'),
759
+ )
760
+ const prefix = head.slice(bound + 1)
761
+ if (
762
+ /(?:^|[^A-Za-z0-9_$])(?:private|fileprivate|static|class)(?:[^A-Za-z0-9_$]|$)/.test(
763
+ prefix,
764
+ )
765
+ )
766
+ continue
767
+ if (!/@objc\b/.test(prefix) && !/@IBAction\b/.test(prefix) && !record.objcMembers)
768
+ continue
769
+ const members = found.get(record.type) ?? new Set<string>()
770
+ members.add(match[2]!)
771
+ found.set(record.type, members)
772
+ }
773
+ }
774
+ return found
775
+ }
776
+
777
+ /** every @objc instance member extensions declare across `sources`, by
778
+ * extended type, for a lowering pass that sees one file at a time. */
779
+ export function objcExtensionMemberIndex(
780
+ sources: Iterable<string>,
781
+ ): Map<string, Set<string>> {
782
+ const index = new Map<string, Set<string>>()
783
+ for (const source of sources) {
784
+ const { tokens } = swiftCodeScan(source)
785
+ const masked = swiftCodeMask(source)
786
+ const records: { type: string; open: number; objcMembers: boolean }[] = []
787
+ let pending: { type: string; objcMembers: boolean } | null = null
788
+ for (const at of tokens) {
789
+ const rest = source.slice(at, at + 600)
790
+ if (rest.startsWith('{')) {
791
+ if (pending) records.push({ ...pending, open: at })
792
+ pending = null
793
+ continue
794
+ }
795
+ if (rest.startsWith('}')) continue
796
+ const extended = EXTENSION_DECL.exec(rest)
797
+ if (extended) {
798
+ const lines = source.lastIndexOf('\n', source.lastIndexOf('\n', at - 1) - 1) + 1
799
+ pending = {
800
+ type: extended[1]!.split('.').pop()!,
801
+ objcMembers: /@objcMembers\b/.test(masked.slice(lines, at)),
802
+ }
803
+ }
804
+ }
805
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, records)) {
806
+ const into = index.get(type) ?? new Set<string>()
807
+ for (const member of members) into.add(member)
808
+ index.set(type, into)
809
+ }
810
+ }
811
+ return index
812
+ }
813
+
814
+ function liftExtensionOverrides(
815
+ source: string,
816
+ extraObjCExtensions?: Map<string, Set<string>>,
817
+ ): string {
613
818
  const { tokens } = swiftCodeScan(source)
819
+ const masked = swiftCodeMask(source)
614
820
  type Frame = { kind: 'class' | 'extension' | 'other'; name: string }
615
821
  const stack: Frame[] = []
616
822
  let pending: Frame | null = null
@@ -620,22 +826,21 @@ function liftExtensionOverrides(source: string): string {
620
826
  >()
621
827
  let declaredBase: string | null = null
622
828
  let declaredObjCMembers = false
829
+ const extensions: { type: string; open: number; objcMembers: boolean }[] = []
830
+ let declaredExtObjCMembers = false
623
831
  const lifted: {
624
832
  type: string
625
833
  member: string
626
- stub: string
834
+ at: number
835
+ modifiers: string[]
836
+ decl: string
837
+ forward: string
838
+ nameAt: number
627
839
  edits: [number, number, string][]
628
840
  }[] = []
841
+ const overrides: { type: string; member: string; at: number; nameAt: number }[] = []
629
842
  // the offset just past the brace that closes the one at `open`
630
- const closing = (open: number): number => {
631
- let depth = 0
632
- for (const at of tokens) {
633
- if (at < open) continue
634
- if (source[at] === '{') depth++
635
- else if (source[at] === '}' && --depth === 0) return at + 1
636
- }
637
- return source.length
638
- }
843
+ const closing = (open: number): number => closingBrace(source, tokens, open)
639
844
  for (const at of tokens) {
640
845
  const rest = source.slice(at, at + 600)
641
846
  if (rest.startsWith('{')) {
@@ -646,6 +851,12 @@ function liftExtensionOverrides(source: string): string {
646
851
  base: declaredBase,
647
852
  objcMembers: declaredObjCMembers,
648
853
  })
854
+ if (frame.kind === 'extension')
855
+ extensions.push({
856
+ type: frame.name,
857
+ open: at,
858
+ objcMembers: declaredExtObjCMembers,
859
+ })
649
860
  stack.push(frame)
650
861
  pending = null
651
862
  continue
@@ -665,12 +876,47 @@ function liftExtensionOverrides(source: string): string {
665
876
  const extended = EXTENSION_DECL.exec(rest)
666
877
  if (extended) {
667
878
  pending = { kind: 'extension', name: extended[1]!.split('.').pop()! }
879
+ const lines = source.lastIndexOf('\n', source.lastIndexOf('\n', at - 1) - 1) + 1
880
+ declaredExtObjCMembers = /@objcMembers\b/.test(masked.slice(lines, at))
668
881
  continue
669
882
  }
670
883
  const top = stack.at(-1)
671
- if (!rest.startsWith('override') || top?.kind !== 'extension' || pending) continue
884
+ if (!rest.startsWith('override') || pending) continue
672
885
  const line = source.slice(source.lastIndexOf('\n', at - 1) + 1, at)
673
886
  const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim())
887
+ if (top?.kind === 'class') {
888
+ let member: string | undefined
889
+ let nameAt = 0
890
+ const direct = OVERRIDE_FUNC.exec(rest)
891
+ if (direct) {
892
+ member = direct[2]
893
+ nameAt =
894
+ at +
895
+ rest.indexOf(
896
+ member!,
897
+ rest.indexOf('func', 'override'.length + direct[1]!.length) + 4,
898
+ )
899
+ } else {
900
+ const property = OVERRIDE_VAR.exec(rest)
901
+ if (property) {
902
+ const open = at + property[0].length - 1
903
+ if (!/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) {
904
+ member = property[2]
905
+ nameAt = at + rest.indexOf(member!, rest.indexOf('var'))
906
+ }
907
+ }
908
+ }
909
+ // a private override is invisible to subclasses on iOS too, so it
910
+ // stays to fail there rather than lowering into a shadowing member.
911
+ if (
912
+ member !== undefined &&
913
+ !modifiers.includes('private') &&
914
+ !modifiers.includes('fileprivate')
915
+ )
916
+ overrides.push({ type: top.name, member, at, nameAt })
917
+ continue
918
+ }
919
+ if (top?.kind !== 'extension') continue
674
920
  const func = OVERRIDE_FUNC.exec(rest)
675
921
  if (func) {
676
922
  const name = func[2]!
@@ -692,21 +938,20 @@ function liftExtensionOverrides(source: string): string {
692
938
  (/\basync\b/.test(clause) ? 'await ' : '') +
693
939
  `__peach_ext_${name}(${args})`
694
940
  const signature = `func ${name}${func[3] ?? ''}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ''}`
941
+ const nameAt =
942
+ at +
943
+ rest.indexOf(name, rest.indexOf('func', 'override'.length + func[1]!.length) + 4)
695
944
  lifted.push({
696
945
  type: top.name,
697
946
  member: name,
698
- stub: `${[...modifiers, 'override'].join(' ')} ${signature} { ${call} };`,
947
+ at,
948
+ modifiers,
949
+ decl: signature,
950
+ forward: `{ ${call} };`,
951
+ nameAt,
699
952
  edits: [
700
953
  [at, 'override'.length, ' '.repeat('override'.length)],
701
- [
702
- at +
703
- rest.indexOf(
704
- name,
705
- rest.indexOf('func', 'override'.length + func[1]!.length) + 4,
706
- ),
707
- 0,
708
- '__peach_ext_',
709
- ],
954
+ [nameAt, 0, '__peach_ext_'],
710
955
  ],
711
956
  })
712
957
  continue
@@ -716,45 +961,96 @@ function liftExtensionOverrides(source: string): string {
716
961
  const open = at + property[0].length - 1
717
962
  if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue
718
963
  const name = property[2]!
964
+ const nameAt = at + rest.indexOf(name, rest.indexOf('var'))
719
965
  lifted.push({
720
966
  type: top.name,
721
967
  member: name,
722
- stub: `${[...modifiers, 'override'].join(' ')} var ${name}: ${property[3]!.trim()} { __peach_ext_${name} };`,
968
+ at,
969
+ modifiers,
970
+ decl: `var ${name}: ${property[3]!.trim()}`,
971
+ forward: `{ __peach_ext_${name} };`,
972
+ nameAt,
723
973
  edits: [
724
974
  [at, 'override'.length, ' '.repeat('override'.length)],
725
- [at + rest.indexOf(name, rest.indexOf('var')), 0, '__peach_ext_'],
975
+ [nameAt, 0, '__peach_ext_'],
726
976
  ],
727
977
  })
728
978
  }
729
979
  }
730
- // whether the member a class inherits is @objc, as an extension override
731
- // needs on iOS: an Apple framework class's members are, and an app class
732
- // in this file declares it with @objc or under @objcMembers. a base this
733
- // file does not declare, or a plain Swift member, is not, and the override
734
- // stays to fail as it does on iOS.
735
- const overridesObjC = (type: string, member: string): boolean => {
980
+ // how the member a class inherits is declared, as an override needs on
981
+ // iOS: `apple` members and `objc` ones (declared with @objc or under
982
+ // @objcMembers in a class body in this file) take `override` in the class
983
+ // as they do on iOS. `ext` is declared with @objc in an extension of a
984
+ // base here or elsewhere in the module: iOS accepts the override, but
985
+ // without an objc runtime no same-name member compiles, so the override
986
+ // drops `override` and is renamed `__peach_ovr_<name>`.
987
+ // a `plain` Swift member or one of an `unknown` base stays as written and
988
+ // fails to compile as it does on iOS.
989
+ const extIndex = new Map<string, Set<string>>()
990
+ if (extraObjCExtensions)
991
+ for (const [type, members] of extraObjCExtensions)
992
+ extIndex.set(type, new Set(members))
993
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, extensions)) {
994
+ const into = extIndex.get(type) ?? new Set<string>()
995
+ for (const member of members) into.add(member)
996
+ extIndex.set(type, into)
997
+ }
998
+ const overrideKind = (type: string, member: string): string => {
736
999
  let base = classes.get(type)?.base ?? null
737
1000
  while (base !== null) {
738
- if (APPLE_CLASS.test(base)) return true
739
1001
  const declaredClass = classes.get(base)
740
- if (!declaredClass) return false
741
- const body = source.slice(declaredClass.brace, closing(declaredClass.brace))
742
- const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body)
743
- if (found) {
744
- const line = body.slice(body.lastIndexOf('\n', found.index) + 1, found.index)
745
- return declaredClass.objcMembers || /@objc\b/.test(line)
746
- }
747
- base = declaredClass.base
1002
+ if (declaredClass) {
1003
+ const body = source.slice(declaredClass.brace, closing(declaredClass.brace))
1004
+ const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body)
1005
+ if (found) {
1006
+ const line = body.slice(body.lastIndexOf('\n', found.index) + 1, found.index)
1007
+ return declaredClass.objcMembers || /@objc\b/.test(line) ? 'objc' : 'plain'
1008
+ }
1009
+ if (extIndex.get(base)?.has(member)) return 'ext'
1010
+ base = declaredClass.base
1011
+ } else if (extIndex.get(base)?.has(member)) return 'ext'
1012
+ else if (APPLE_CLASS.test(base)) return 'apple'
1013
+ else return 'unknown'
748
1014
  }
749
- return false
1015
+ return 'unknown'
750
1016
  }
1017
+ // an ext override takes `__peach_ovr_<name>`: without an objc runtime
1018
+ // no same-name member compiles, with `override`, @nonobjc or the @ObjC
1019
+ // macro's same-named static accessors alike. the renamed member keeps its
1020
+ // body and lines; callers keep binding the base member (a known
1021
+ // divergence, reported with the slice).
1022
+ const rename = (at: number, nameAt: number): [number, number, string][] => [
1023
+ [at, 'override'.length, ' '.repeat('override'.length)],
1024
+ [nameAt, 0, '__peach_ovr_'],
1025
+ ]
751
1026
  const edits: [number, number, string][] = []
752
1027
  const stubs = new Map<number, string[]>()
753
1028
  for (const entry of lifted) {
754
1029
  const brace = classes.get(entry.type)?.brace
755
- if (brace === undefined || !overridesObjC(entry.type, entry.member)) continue
1030
+ if (brace === undefined) continue
1031
+ const kind = overrideKind(entry.type, entry.member)
1032
+ if (kind !== 'apple' && kind !== 'objc' && kind !== 'ext') continue
1033
+ // a private override is invisible to subclasses on iOS too, so it stays
1034
+ // to fail there rather than lowering into a shadowing member.
1035
+ if (
1036
+ kind === 'ext' &&
1037
+ (entry.modifiers.includes('private') || entry.modifiers.includes('fileprivate'))
1038
+ )
1039
+ continue
1040
+ if (kind === 'ext') {
1041
+ edits.push(...rename(entry.at, entry.nameAt))
1042
+ continue
1043
+ }
756
1044
  edits.push(...entry.edits)
757
- stubs.set(brace, [...(stubs.get(brace) ?? []), entry.stub])
1045
+ const head = [...entry.modifiers, 'override'].filter((word) => word !== '').join(' ')
1046
+ stubs.set(brace, [
1047
+ ...(stubs.get(brace) ?? []),
1048
+ `${head} ${entry.decl} ${entry.forward}`,
1049
+ ])
1050
+ }
1051
+ for (const candidate of overrides) {
1052
+ if (overrideKind(candidate.type, candidate.member) !== 'ext') continue
1053
+ edits.push(...rename(candidate.at, candidate.nameAt))
758
1054
  }
759
1055
  for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(' ')}`])
760
1056
  let out = source
@@ -974,8 +1270,11 @@ function swiftCodeMask(source: string): string {
974
1270
  return chars.join('')
975
1271
  }
976
1272
 
977
- export function swiftSourceAsIOS(original: string): string {
978
- const source = liftExtensionOverrides(original)
1273
+ export function swiftSourceAsIOS(
1274
+ original: string,
1275
+ extraObjCExtensions?: Map<string, Set<string>>,
1276
+ ): string {
1277
+ const source = liftExtensionOverrides(original, extraObjCExtensions)
979
1278
  const { lineStarts, tokens } = swiftCodeScan(source)
980
1279
  let offset = 0
981
1280
  // equal width, so every token offset still holds
@@ -1179,8 +1478,12 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
1179
1478
  return { lineStarts: starts, tokens }
1180
1479
  }
1181
1480
 
1182
- const compiledSource = (file: string, contents: string) =>
1183
- file.endsWith('.swift') ? swiftSourceAsIOS(contents) : contents
1481
+ const compiledSource = (
1482
+ file: string,
1483
+ contents: string,
1484
+ extraObjCExtensions?: Map<string, Set<string>>,
1485
+ ) =>
1486
+ file.endsWith('.swift') ? swiftSourceAsIOS(contents, extraObjCExtensions) : contents
1184
1487
 
1185
1488
  /** a dependency package's build copy: the published tree with every Swift
1186
1489
  * source rewritten as app sources are, so an unchanged upstream package that
@@ -1188,6 +1491,25 @@ const compiledSource = (file: string, contents: string) =>
1188
1491
  * published and the upstream tree is never written. */
1189
1492
  export function prepareSwiftDependency(source: string, destination: string): void {
1190
1493
  rmSync(destination, { recursive: true, force: true })
1494
+ // an override in one file may answer an @objc member an extension
1495
+ // declares in another, so the module-wide member index precedes the copy.
1496
+ const origins: string[] = []
1497
+ const gather = (from: string, root: boolean) => {
1498
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
1499
+ if (entry.name === '.git' || entry.name === '.build' || entry.name === '.swiftpm')
1500
+ continue
1501
+ const file = path.join(from, entry.name)
1502
+ if (entry.isDirectory()) gather(file, false)
1503
+ else if (
1504
+ entry.isFile() &&
1505
+ entry.name.endsWith('.swift') &&
1506
+ !(root && /^Package(@swift-[\d.]+)?\.swift$/.test(entry.name))
1507
+ )
1508
+ origins.push(readFileSync(file, 'utf8'))
1509
+ }
1510
+ }
1511
+ gather(source, true)
1512
+ const objcExtensions = objcExtensionMemberIndex(origins)
1191
1513
  const copy = (from: string, to: string, root: boolean) => {
1192
1514
  mkdirSync(to, { recursive: true })
1193
1515
  for (const entry of readdirSync(from, { withFileTypes: true })) {
@@ -1201,7 +1523,10 @@ export function prepareSwiftDependency(source: string, destination: string): voi
1201
1523
  entry.name.endsWith('.swift') &&
1202
1524
  !(root && /^Package(@swift-[\d.]+)?\.swift$/.test(entry.name))
1203
1525
  )
1204
- writeFileSync(target, compiledSource(file, readFileSync(file, 'utf8')))
1526
+ writeFileSync(
1527
+ target,
1528
+ compiledSource(file, readFileSync(file, 'utf8'), objcExtensions),
1529
+ )
1205
1530
  else cpSync(file, target, { verbatimSymlinks: true })
1206
1531
  }
1207
1532
  }
@@ -1255,10 +1580,20 @@ export function writeSwiftProject(
1255
1580
  .digest('hex')
1256
1581
  .slice(0, 16)
1257
1582
  const moduleFiles = `\n// sootsim-swift files ${modulePlan.digest('hex').slice(0, 16)}\n// resource accessors ${resourcePlan}\n`
1583
+ // an override in one file may answer an @objc member an extension
1584
+ // declares in another, so the module-wide member index precedes the copy.
1585
+ const objcExtensions = objcExtensionMemberIndex(
1586
+ Object.entries(input.files)
1587
+ .filter(([file]) => file.endsWith('.swift'))
1588
+ .map(([, contents]) => contents),
1589
+ )
1258
1590
  if (targets.length === 0) {
1259
1591
  for (const [file, contents] of Object.entries(input.files)) {
1260
1592
  if (file === 'Package.swift') continue
1261
- files.set(path.join(layout.sources, file), compiledSource(file, contents))
1593
+ files.set(
1594
+ path.join(layout.sources, file),
1595
+ compiledSource(file, contents, objcExtensions),
1596
+ )
1262
1597
  }
1263
1598
  let manifest = readFileSync(
1264
1599
  path.join(moduleRoot, 'scripts/contrast-app-Package.swift'),
@@ -1307,7 +1642,7 @@ export function writeSwiftProject(
1307
1642
  const base = layout.multi ? layout.root : layout.sources
1308
1643
  for (const [file, contents] of Object.entries(input.files)) {
1309
1644
  if (file === 'Package.swift') continue
1310
- files.set(path.join(base, file), compiledSource(file, contents))
1645
+ files.set(path.join(base, file), compiledSource(file, contents, objcExtensions))
1311
1646
  }
1312
1647
  files.set(
1313
1648
  path.join(layout.root, 'Package.swift'),