peachsim 0.1.2609 → 0.1.2610

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 (147) hide show
  1. package/cli/commands/perf-native.ts +120 -6
  2. package/dist-lib/agent-daemon-client.cjs +1 -1
  3. package/dist-lib/agent-events.cjs +1 -1
  4. package/dist-lib/attached-projects.cjs +1 -1
  5. package/dist-lib/auth/shared-session.cjs +1 -1
  6. package/dist-lib/backend-origin.cjs +1 -1
  7. package/dist-lib/beta.cjs +1 -1
  8. package/dist-lib/beta.mjs +2 -2
  9. package/dist-lib/bridge-constants.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.cjs +1 -1
  11. package/dist-lib/bridge-contract-input.mjs +5 -5
  12. package/dist-lib/bridge-contract.cjs +1 -1
  13. package/dist-lib/bridge-contract.mjs +3 -3
  14. package/dist-lib/bundle-channel.cjs +60485 -60177
  15. package/dist-lib/capture-contract.cjs +1 -1
  16. package/dist-lib/capture-contract.mjs +3 -3
  17. package/dist-lib/cloud-contract.cjs +1 -1
  18. package/dist-lib/cloud-contract.mjs +3 -3
  19. package/dist-lib/cloud-test-args.cjs +1 -1
  20. package/dist-lib/cloud-test-args.mjs +2 -2
  21. package/dist-lib/cloud.cjs +1 -1
  22. package/dist-lib/cloud.mjs +7 -7
  23. package/dist-lib/config.cjs +1 -1
  24. package/dist-lib/config.mjs +5 -5
  25. package/dist-lib/detox/index.cjs +1 -1
  26. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  27. package/dist-lib/esm-chunks/{acorn-P6Q3SN6U.mjs → acorn-L2SFCOHG.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-CJLXAXGU.mjs → chunk-2LJTZ2KG.mjs} +17 -328
  29. package/dist-lib/esm-chunks/{chunk-DN4RY4ZO.mjs → chunk-42NDD4R7.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-MF7HNQ5K.mjs → chunk-73NIGS7D.mjs} +1490 -3950
  31. package/dist-lib/esm-chunks/{chunk-LSNKOL3L.mjs → chunk-CUBTZPSZ.mjs} +1 -1
  32. package/dist-lib/esm-chunks/chunk-EU5WMP5O.mjs +322 -0
  33. package/dist-lib/esm-chunks/{chunk-7JYSTMRO.mjs → chunk-EYSNLE5V.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-UMKSCALR.mjs → chunk-FP447MCW.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-2UJG76LY.mjs → chunk-HMTSU22Q.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-GJZ2ROIK.mjs → chunk-KTAGV5U6.mjs} +14 -12
  37. package/dist-lib/esm-chunks/{chunk-3MJN4KBR.mjs → chunk-MJP4WOSX.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-3LX34QVB.mjs → chunk-MK4DOEDN.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-4HCHYS5S.mjs → chunk-N3M5KT33.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-IHK4FK5A.mjs → chunk-N7XU2WWO.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-D44BCQPZ.mjs → chunk-RN73P2DY.mjs} +34 -28
  42. package/dist-lib/esm-chunks/{chunk-62CUUMJF.mjs → chunk-VDLPNJ6P.mjs} +1 -1
  43. package/dist-lib/esm-chunks/chunk-W3LNUIUA.mjs +2655 -0
  44. package/dist-lib/esm-chunks/{chunk-T554RY2B.mjs → chunk-WBQFHIGS.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-5V7JOQMI.mjs → chunk-WZHEW7Z7.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-FOM5H3FB.mjs → chunk-X74N3K5N.mjs} +4 -4
  47. package/dist-lib/esm-chunks/{chunk-ZUBTL7EH.mjs → chunk-XN74REO2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-PKXGC5OZ.mjs → chunk-YLUD2UET.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{chunk-VHBBOWKT.mjs → chunk-YVLXYLNV.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-L4ATOCRX.mjs → chunk-YYGSN3BN.mjs} +3 -3
  51. package/dist-lib/esm-chunks/{chunk-FIUWBFDV.mjs → chunk-ZZB2LFYV.mjs} +1 -1
  52. package/dist-lib/esm-chunks/{metro-layout-parser-7VIYXTX3.mjs → metro-layout-parser-VDPXJ7LW.mjs} +3 -3
  53. package/dist-lib/esm-chunks/{swift-package-prebuilt-GNRGNGKJ.mjs → swift-package-prebuilt-HRPDLN2P.mjs} +14 -11
  54. package/dist-lib/esm-chunks/{swift-sdk-app-module-QMYD4WKD.mjs → swift-sdk-app-module-5DOGMU3M.mjs} +16 -14
  55. package/dist-lib/esm-chunks/{swift-sdk-image-LUAWELUR.mjs → swift-sdk-image-W3UU4H4L.mjs} +16 -14
  56. package/dist-lib/esm-chunks/{swift-sdk-image-producer-A4Y2EYPV.mjs → swift-sdk-image-producer-OJWD6ZOH.mjs} +8 -6
  57. package/dist-lib/expo-swift-bundle.cjs +42524 -42216
  58. package/dist-lib/expo-swift-metadata.cjs +1 -1
  59. package/dist-lib/expo-swift-metadata.mjs +7 -7
  60. package/dist-lib/home-paths.cjs +1 -1
  61. package/dist-lib/host/bridge-host.cjs +43719 -43248
  62. package/dist-lib/host/fetch-proxy-handler.cjs +670 -645
  63. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  64. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  65. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  66. package/dist-lib/host/websocket-proxy.cjs +1 -1
  67. package/dist-lib/index.cjs +1 -1
  68. package/dist-lib/kotlin-host.cjs +1 -1
  69. package/dist-lib/menu.cjs +1 -1
  70. package/dist-lib/menu.mjs +3 -3
  71. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  72. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  73. package/dist-lib/metro-production-bundle.cjs +1 -1
  74. package/dist-lib/metro-production-bundle.mjs +4 -4
  75. package/dist-lib/native-app-identity-project.cjs +1499 -2889
  76. package/dist-lib/native-app-identity-project.mjs +317 -339
  77. package/dist-lib/native-app-identity.cjs +1 -1
  78. package/dist-lib/native-app-identity.mjs +6 -6
  79. package/dist-lib/native-firebase-metadata.cjs +1 -1
  80. package/dist-lib/native-firebase-metadata.mjs +3 -3
  81. package/dist-lib/pdfium-raster.cjs +1 -1
  82. package/dist-lib/pdfium-raster.mjs +2 -2
  83. package/dist-lib/plist.cjs +1 -1
  84. package/dist-lib/plist.mjs +3 -3
  85. package/dist-lib/profiles.cjs +1 -1
  86. package/dist-lib/public-brand.cjs +1 -1
  87. package/dist-lib/public-origins-lib-esm.json +166 -154
  88. package/dist-lib/public-origins-lib.json +141 -198
  89. package/dist-lib/react-native-host-modules.cjs +1 -1
  90. package/dist-lib/react-native-host-modules.mjs +2 -2
  91. package/dist-lib/reap-browser.cjs +1 -1
  92. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  93. package/dist-lib/sdk.cjs +1 -1
  94. package/dist-lib/sdk.mjs +8 -8
  95. package/dist-lib/skills.cjs +38909 -38438
  96. package/dist-lib/swift-compile.cjs +12239 -12121
  97. package/dist-lib/swift-compile.mjs +36 -33
  98. package/dist-lib/swift-package.cjs +1 -1
  99. package/dist-lib/swift-package.mjs +3 -3
  100. package/dist-lib/swift-submit.cjs +1 -1
  101. package/dist-lib/swift-submit.mjs +6 -6
  102. package/dist-lib/swift-svg-raster.cjs +1 -1
  103. package/dist-lib/swift-svg-raster.mjs +2 -2
  104. package/dist-lib/swift-toolchain.cjs +1 -1
  105. package/dist-lib/swift.cjs +1 -1
  106. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  108. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  109. package/dist-lib/vendor/acorn.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/stream-json.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase.cjs +1 -1
  117. package/dist-lib/vendor/terser.cjs +1 -1
  118. package/dist-lib/vendor/valibot.cjs +1 -1
  119. package/dist-lib/vendor/ws.cjs +1 -1
  120. package/dist-lib/vendor/zod.cjs +1 -1
  121. package/dist-lib/worklet-executable.cjs +1 -1
  122. package/dist-lib/worklet-executable.mjs +3 -3
  123. package/package.json +1 -1
  124. package/src/binaryen.lock.json +3 -3
  125. package/src/genrule-archives.ts +5 -2
  126. package/src/native-framework-compiler.ts +1 -1
  127. package/src/native-static-libraries.ts +2 -3
  128. package/src/native-swift-slices.ts +1 -1
  129. package/src/nitro-dependencies.ts +3 -7
  130. package/src/one-native-controls-package.ts +165 -11
  131. package/src/oneNativeControlsContract.ts +1 -0
  132. package/src/rive-runtime-dependencies.ts +1 -2
  133. package/src/swift-compile.ts +165 -1796
  134. package/src/swift-compiler-digest.ts +2 -0
  135. package/src/swift-distribution.ts +39 -15
  136. package/src/swift-objc-compile.ts +194 -32
  137. package/src/swift-package-manifest.ts +6 -29
  138. package/src/swift-packages.ts +6 -14
  139. package/src/swift-sdk-surface.ts +1811 -0
  140. package/src/swift-standin-digest.ts +28 -5
  141. package/src/swift-standins.ts +16 -19
  142. package/src/swift-wasm-archive.ts +200 -0
  143. package/src/swift-wasm-prune.ts +3 -93
  144. package/src/swift-wasm64-native-source.ts +4 -2
  145. package/src/swiftWasm64ConfigContract.ts +10 -0
  146. package/src/wasm-optimize.ts +18 -14
  147. package/src/xcode-project.ts +2 -4
@@ -1,10 +1,4 @@
1
- import {
2
- spawn,
3
- spawnSync,
4
- execFileSync,
5
- type ExecFileOptions,
6
- type SpawnOptions,
7
- } from 'node:child_process'
1
+ import { spawn, type ExecFileOptions, type SpawnOptions } from 'node:child_process'
8
2
  import { createHash, randomUUID } from 'node:crypto'
9
3
  import {
10
4
  chmodSync,
@@ -45,10 +39,8 @@ import {
45
39
  } from './swift-darwin-records'
46
40
  import { designTimeDiagnostic, designTimeSource } from './swift-design-time'
47
41
  import {
48
- parseSwiftDistributionManifest,
49
- SWIFT_DISTRIBUTION_MANIFEST,
50
- type SwiftDistributionManifest,
51
42
  SWIFT_DISTRIBUTION_OBJC_SELECTORS,
43
+ type SwiftDistributionManifest,
52
44
  } from './swift-distribution-contract'
53
45
  import {
54
46
  SWIFT_DISTRIBUTION_MIRROR,
@@ -101,8 +93,6 @@ import {
101
93
  OBJC_RESOURCE_ACCESSOR_BODY,
102
94
  OBJC_RESOURCE_ACCESSOR_HEADER,
103
95
  swiftManifestCxxLanguageStandard,
104
- swiftImplicitResourcePaths,
105
- swiftManifestDeclarations,
106
96
  swiftManifestTargets,
107
97
  swiftManifestPackages,
108
98
  swiftObjCResourceAccessor,
@@ -137,11 +127,45 @@ import {
137
127
  } from './swift-root-lock'
138
128
  import { orderObjCConstructors } from './swift-sdk-image-wasm'
139
129
  import {
140
- swiftSharedSdkInputFiles,
141
- swiftSharedSdkRoot,
142
- swiftSharedSdkSourceRoot,
143
- swiftSharedSdkViewOptions,
144
- } from './swift-shared-sdk'
130
+ cActiveCode,
131
+ clangInterfaceHeader,
132
+ clearLinkedModuleDigests,
133
+ CORE_FOUNDATION_OVERLAY_GLOBALS,
134
+ emptyMacroEnvironment,
135
+ FOUNDATION_IMPLICIT_MODULES,
136
+ foundationOwnerOf,
137
+ nativelyDeclaredFunctions,
138
+ NON_IOS_MODULES,
139
+ objcEnumerations,
140
+ REACH_STAGED_FRAMEWORKS,
141
+ sdkObjCDeclarationOwners,
142
+ stripCCode,
143
+ swiftBuildJobs,
144
+ swiftCDefinedNames,
145
+ swiftCodeMask,
146
+ swiftCompileSdkOptions,
147
+ swiftCompileSurfaceDigest,
148
+ swiftConditionalLines,
149
+ swiftCTakesReturnAddress,
150
+ swiftDistributionAt,
151
+ swiftDistributionCompileView,
152
+ swiftHeaderWithSuperclassImports,
153
+ swiftImportNames,
154
+ swiftInterfaceDeclarations,
155
+ swiftMacroPlugins,
156
+ swiftModuleDigest,
157
+ swiftModuleInputFiles,
158
+ swiftModuleInterface,
159
+ swiftModuleSdk,
160
+ swiftPeachModules,
161
+ swiftSdkPaths,
162
+ wasmMacroEnvironment,
163
+ withFrameworkCompanionImports,
164
+ withoutImportedSdkEnumForwards,
165
+ withoutSwiftDeclarations,
166
+ type SwiftCMacroEnvironment,
167
+ } from './swift-sdk-surface'
168
+ import { swiftSharedSdkRoot } from './swift-shared-sdk'
145
169
  import { collectSwiftSourceClosure } from './swift-source-closure'
146
170
  import {
147
171
  refreshSwiftCacheHold,
@@ -152,10 +176,8 @@ import {
152
176
  swiftEnvironment,
153
177
  swiftPackageCacheOptions,
154
178
  swiftSdkOptions,
155
- swiftSourceSdk,
156
179
  swiftToolchain,
157
180
  writeSwiftAutolinkLinker,
158
- type SwiftWasmSdk,
159
181
  } from './swift-toolchain'
160
182
  import { compileUniformTypeConstants } from './swift-uniform-type-constants'
161
183
  import { pruneSwiftWasmLink, readArMembers } from './swift-wasm-prune'
@@ -194,10 +216,34 @@ export {
194
216
  brotliCompressQ11,
195
217
  brotliCompressQ4,
196
218
  brotliCompressQ6,
219
+ clearLinkedModuleDigests,
220
+ FOUNDATION_IMPLICIT_MODULES,
221
+ foundationOwnerOf,
222
+ REACH_STAGED_FRAMEWORKS,
223
+ swiftBuildJobs,
224
+ swiftCDefinedNames,
225
+ swiftCodeMask,
226
+ swiftCompileSdkOptions,
227
+ swiftCompileSurfaceDigest,
228
+ swiftCTakesReturnAddress,
229
+ swiftDistributionAt,
230
+ swiftHeaderWithSuperclassImports,
197
231
  swiftIcuAddress,
198
232
  swiftIcuAsset,
199
233
  swiftIcuBundleAsset,
200
234
  swiftIcuPacked,
235
+ swiftImportNames,
236
+ swiftInterfaceDeclarations,
237
+ swiftMacroPlugins,
238
+ swiftModuleDigest,
239
+ swiftModuleInputFiles,
240
+ swiftModuleInterface,
241
+ swiftModuleSdk,
242
+ swiftPeachModules,
243
+ swiftSdkPaths,
244
+ withFrameworkCompanionImports,
245
+ withoutSwiftDeclarations,
246
+ type SwiftCMacroEnvironment,
201
247
  type SwiftIcuAsset,
202
248
  }
203
249
 
@@ -332,24 +378,6 @@ const SWIFTPM_PROGRESS = /^\[\d+\/\d+\] /
332
378
  const SWIFTPM_NOISE =
333
379
  /^(?:\[\d+\/\d+\] |Building for production\.\.\.$|warning: '--build-system native' has been deprecated)/
334
380
 
335
- export function swiftBuildJobs(): number {
336
- const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES)
337
- const parallelism = Math.max(1, os.availableParallelism())
338
- if (!Number.isInteger(admittedCores) || admittedCores <= 0)
339
- return Math.min(4, Math.max(1, Math.floor(parallelism / 2)))
340
- const cores = Math.min(admittedCores, parallelism)
341
- if (process.platform === 'darwin') return cores
342
- const memory =
343
- process.env.TM_EXEC_ADMITTED === '1' && process.env.LINUX_BUILD_SCOPE
344
- ? Number(process.env.TM_EXEC_LINUX_MEMORY_MAX)
345
- : NaN
346
- const memoryJobs =
347
- Number.isSafeInteger(memory) && memory > 0
348
- ? Math.max(1, Math.floor(memory / (2 * 1024 ** 3)))
349
- : 8
350
- return Math.min(cores, memoryJobs)
351
- }
352
-
353
381
  function swiftCompilerJobs(): number {
354
382
  return Math.min(32, swiftBuildJobs(), Math.max(1, Math.floor(os.totalmem() / 2 ** 31)))
355
383
  }
@@ -499,374 +527,6 @@ export interface SwiftProjectLayout {
499
527
  multi: boolean
500
528
  }
501
529
 
502
- /**
503
- * the prebuilt distribution at a module root, or null for a sootsim-swift
504
- * source checkout. an installed peach links the distribution: compiled
505
- * modules, one static library and host macro plugins, and no source
506
- * (docs/peach/swift/distribution.md).
507
- */
508
- export function swiftDistributionAt(root: string): SwiftDistributionManifest | null {
509
- const file = path.join(root, SWIFT_DISTRIBUTION_MANIFEST)
510
- const stat = statSync(file, { bigint: true, throwIfNoEntry: false })
511
- if (!stat) return null
512
- // a large app asks once per target; the megabytes of manifest parse once
513
- // per published file.
514
- const identity = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}`
515
- const cached = distributionManifests.get(file)
516
- if (cached?.identity === identity) return cached.manifest
517
- const manifest = parseSwiftDistributionManifest(JSON.parse(readFileSync(file, 'utf8')))
518
- distributionManifests.set(file, { identity, manifest })
519
- return manifest
520
- }
521
- const distributionManifests = new Map<
522
- string,
523
- { identity: string; manifest: SwiftDistributionManifest }
524
- >()
525
-
526
- // the selector map and host macro plugins every app compile names, at a path
527
- // named by their bytes: a change to either changes every compile command.
528
- const distributionCompileViews = new WeakMap<SwiftDistributionManifest, string>()
529
- function swiftDistributionCompileView(
530
- moduleRoot: string,
531
- distribution: SwiftDistributionManifest,
532
- ): string {
533
- let view = distributionCompileViews.get(distribution)
534
- if (!view || !existsSync(view)) {
535
- const inputs = Object.entries(distribution.files)
536
- .filter(
537
- ([file]) =>
538
- file.startsWith('host/') || file === SWIFT_DISTRIBUTION_OBJC_SELECTORS,
539
- )
540
- .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
541
- const digest = createHash('sha256').update(JSON.stringify(inputs)).digest('hex')
542
- view = path.join(swiftCacheDir(), 'swift-sdk-views', `compile-${digest}`)
543
- if (!existsSync(view)) {
544
- mkdirSync(path.dirname(view), { recursive: true })
545
- const staging = mkdtempSync(`${view}-`)
546
- try {
547
- chmodSync(staging, 0o755)
548
- for (const [file] of inputs) {
549
- if (!isSwiftResourcePath(file))
550
- throw new Error(`invalid Swift distribution compile path ${file}`)
551
- const destination = path.join(staging, file)
552
- mkdirSync(path.dirname(destination), { recursive: true })
553
- copyFileSync(path.join(moduleRoot, file), destination)
554
- }
555
- try {
556
- renameSync(staging, view)
557
- } catch (error) {
558
- if (!existsSync(view)) throw error
559
- }
560
- } finally {
561
- rmSync(staging, { recursive: true, force: true })
562
- }
563
- }
564
- distributionCompileViews.set(distribution, view)
565
- }
566
- const now = new Date()
567
- utimesSync(view, now, now)
568
- refreshSwiftCacheHold(view)
569
- return view
570
- }
571
-
572
- /**
573
- * frameworks without Swift declarations that stage by the headers consumers
574
- * import: React's umbrella imports UIKit headers (UIKeyCommand, UIFontMetrics,
575
- * UIAccessibilityElement) the sdk's clang UIKit surface does not carry. an
576
- * app's React headers never take Peach's React interface, whose generated
577
- * header imports a React/React.h the prebuilt framework lacks.
578
- */
579
- export const REACH_STAGED_FRAMEWORKS: ReadonlySet<string> = new Set(['React'])
580
-
581
- /**
582
- * the Objective-C interface an SDK module defines: the names Swift owns and
583
- * its generated header. a distribution ships the header; a source checkout
584
- * names them by `@objc(Name)` and reads the header its module build emitted
585
- * (`.build/host`). a module with no emitted header has no interface in either,
586
- * so its original Objective-C headers keep their declarations.
587
- */
588
- export function swiftModuleInterface(
589
- moduleRoot: string,
590
- name: string,
591
- ): { declared: ReadonlySet<string>; header: string } | null {
592
- if (REACH_STAGED_FRAMEWORKS.has(name)) return null
593
- if (swiftDistributionAt(moduleRoot)) {
594
- const file = path.join(moduleRoot, 'modules', `${name}-Swift.h`)
595
- if (!existsSync(file)) return null
596
- const header = clangInterfaceHeader(readFileSync(file, 'utf8'), moduleRoot)
597
- return { declared: swiftInterfaceDeclarations(header), header }
598
- }
599
- const sources = path.join(moduleRoot, 'Sources', name)
600
- const built = path.join(moduleRoot, '.build/host', `${name}-Swift.h`)
601
- if (!existsSync(sources) || !existsSync(built)) return null
602
- const declared = new Set<string>()
603
- for (const file of readdirSync(sources, { recursive: true, encoding: 'utf8' }))
604
- if (file.endsWith('.swift'))
605
- // an NSObject subclass is an Objective-C class named as it is in Swift
606
- for (const [, objc, subclass] of readFileSync(
607
- path.join(sources, file),
608
- 'utf8',
609
- ).matchAll(
610
- /@objc\((\w+)\)\s+(?:\w+\s+)*?(?:protocol|class)\s|^(?:public|open)\s+(?:final\s+)?class\s+(\w+)\s*:\s*NSObject\b/gm,
611
- ))
612
- declared.add((objc ?? subclass)!)
613
- if (declared.size === 0) return null
614
- return {
615
- declared,
616
- header: clangInterfaceHeader(readFileSync(built, 'utf8'), moduleRoot),
617
- }
618
- }
619
-
620
- // the compiler imports the module that defines a type, and UIKit's declarations
621
- // live in UIKitCore/UIKitText, which only the umbrella UIKit module represents
622
- // to clang. CoreFoundation's CGFloat lives in the Swift CoreFoundation overlay,
623
- // while clang's Foundation umbrella owns public Core Foundation types,
624
- // networking classes and the classes PeachFoundation implements. a framework's
625
- // enums and constants clang target repeats declarations its headers own.
626
- function clangInterfaceHeader(header: string, moduleRoot: string): string {
627
- const distribution = swiftDistributionAt(moduleRoot) !== null
628
- const frameworks = path.join(
629
- swiftSharedSdkSourceRoot(moduleRoot, distribution),
630
- 'System/Library/Frameworks',
631
- )
632
- let references: Set<string> | undefined
633
- const imported = new Set(
634
- [...header.matchAll(/^@import (\w+);$/gm)].map((match) => match[1]!),
635
- )
636
- return header
637
- .replace(/^@import (?:UIKitCore|UIKitText);$/gm, '@import UIKit;')
638
- .replace(
639
- /^@import ((\w+?)(?:Enums|Constants));$/gm,
640
- (_, module: string, framework: string) => {
641
- const imports = [`@import ${framework};`]
642
- imported.add(framework)
643
- const directory = distribution
644
- ? path.join(moduleRoot, 'modules', module)
645
- : path.join(moduleRoot, 'Sources', module, 'include')
646
- if (!existsSync(directory)) return imports[0]!
647
-
648
- if (!references) {
649
- references = new Set(header.match(/\b[A-Z]\w*\b/g))
650
- for (const name of objcEnumerations(header)) references.delete(name)
651
- }
652
- const owners = sdkObjCDeclarationOwners(frameworks)
653
- for (const name of clangDeclarationEnums(directory)) {
654
- const owner = references.has(name) ? owners.get(name) : undefined
655
- if (!owner || imported.has(owner)) continue
656
- imported.add(owner)
657
- imports.push(`@import ${owner};`)
658
- }
659
- return imports.join('\n')
660
- },
661
- )
662
- .replace(
663
- /^@import (?:CoreFoundation(?:_Private)?|FoundationNetworking|PeachFoundation);$/gm,
664
- '@import Foundation;',
665
- )
666
- .replace(/\b_TtC10Foundation\d+(NS\w+)\b/g, '$1')
667
- .replace(/\b__attribute__\(\(objc_subclassing_restricted\)\)\s*/g, '')
668
- }
669
-
670
- const objcEnumerations = (header: string): string[] =>
671
- [
672
- ...header.matchAll(
673
- /^\s*typedef\s+(?:NS|CF|SWIFT)_\w*(?:ENUM|OPTIONS)\w*\s*\(\s*\w+\s*,\s*(\w+)\b/gm,
674
- ),
675
- ].map((match) => match[1]!)
676
-
677
- const clangDeclarationEnumCache = new Map<string, string[]>()
678
- function clangDeclarationEnums(directory: string): string[] {
679
- const cached = clangDeclarationEnumCache.get(directory)
680
- if (cached) return cached
681
- const enums = readdirSync(directory)
682
- .filter((file) => file.endsWith('.h'))
683
- .flatMap((file) => objcEnumerations(readFileSync(path.join(directory, file), 'utf8')))
684
- clangDeclarationEnumCache.set(directory, enums)
685
- return enums
686
- }
687
-
688
- const objcEnumForward = /^[ \t]*SWIFT_ENUM_FWD_DECL\s*\(\s*\w+\s*,\s*(\w+)\b/
689
-
690
- function withoutImportedSdkEnumForwards(
691
- header: string,
692
- owners: ReadonlyMap<string, string>,
693
- ): string {
694
- const imports = new Set([...header.matchAll(/^@import (\w+);$/gm)].map((m) => m[1]!))
695
- return header
696
- .split('\n')
697
- .filter((line) => {
698
- const name = objcEnumForward.exec(line)?.[1]
699
- const owner = name && owners.get(name)
700
- return !owner || !imports.has(owner)
701
- })
702
- .join('\n')
703
- }
704
-
705
- /** the @_cdecl functions a generated header declares that one of the native header texts also declares. */
706
- function nativelyDeclaredFunctions(
707
- generated: string,
708
- headers: Iterable<string>,
709
- ): string[] {
710
- const candidates = [
711
- ...new Set(
712
- [...generated.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
713
- (match) => match[1]!,
714
- ),
715
- ),
716
- ]
717
- if (candidates.length === 0) return []
718
- const declaration = new RegExp(`^[^\\n#/*]*?\\b(${candidates.join('|')})\\s*\\(`, 'gm')
719
- const found = new Set<string>()
720
- for (const header of headers)
721
- for (const match of header.matchAll(declaration)) found.add(match[1]!)
722
- return [...found]
723
- }
724
-
725
- const sdkDeclarationOwners = new Map<string, Map<string, string>>()
726
- /** the framework whose headers define each Objective-C class, protocol and enumeration in an SDK's frameworks directory. */
727
- function sdkObjCDeclarationOwners(frameworks: string): Map<string, string> {
728
- const known = sdkDeclarationOwners.get(frameworks)
729
- if (known) return known
730
- const owners = new Map<string, string>()
731
- for (const framework of readdirSync(frameworks))
732
- if (framework.endsWith('.framework')) {
733
- const headers = path.join(frameworks, framework, 'Headers')
734
- if (existsSync(headers))
735
- for (const file of readdirSync(headers, { recursive: true, encoding: 'utf8' }))
736
- if (file.endsWith('.h')) {
737
- const header = readFileSync(path.join(headers, file), 'utf8')
738
- for (const name of [
739
- ...swiftInterfaceDeclarations(header),
740
- ...objcEnumerations(header),
741
- ...[
742
- ...header.matchAll(/^[A-Z_]*_(?:EXTERN|EXPORT)\b[^;(\n]*?\b(\w+)\s*\(/gm),
743
- ].map((match) => match[1]!),
744
- ])
745
- owners.set(name, framework.slice(0, -'.framework'.length))
746
- }
747
- }
748
- sdkDeclarationOwners.set(frameworks, owners)
749
- return owners
750
- }
751
-
752
- export function swiftHeaderWithSuperclassImports(
753
- header: string,
754
- interfaceFor: (
755
- name: string,
756
- ) => { file: string; header: string; module: boolean } | null,
757
- ): string {
758
- const superclasses = new Set(
759
- [...header.matchAll(/@interface\s+\w+\s*:\s*(\w+)/g)].map((match) => match[1]!),
760
- )
761
- return header.replace(/^@import (\w+);$/gm, (statement, name: string) => {
762
- const dependency = interfaceFor(name)
763
- // a framework peach implements only in swift has no clang module to
764
- // import; its objective-c surface is the generated interface alone
765
- if (dependency && !dependency.module)
766
- return `#import ${JSON.stringify(dependency.file)}`
767
- if (
768
- !dependency ||
769
- ![...swiftInterfaceDeclarations(dependency.header)].some((name) =>
770
- superclasses.has(name),
771
- )
772
- )
773
- return statement
774
- return `${statement}\n#import ${JSON.stringify(dependency.file)}`
775
- })
776
- }
777
-
778
- /** the Objective-C protocols and classes a generated interface header defines. */
779
- export const swiftInterfaceDeclarations = (header: string): Set<string> =>
780
- new Set([
781
- ...[
782
- ...header.matchAll(
783
- /^[ \t]*(?:[A-Z_]\w*(?:\([^()\n]*\))?[ \t]+)*@protocol\s+(\w+)\b(?![^\n]*;\s*$)/gm,
784
- ),
785
- ].map((m) => m[1]!),
786
- ...[
787
- ...header.matchAll(
788
- /^[ \t]*(?:[A-Z_]\w*(?:\([^()\n]*\))?[ \t]+)*@interface\s+(\w+)\s*(?=[:<{]|$)/gm,
789
- ),
790
- ].map((m) => m[1]!),
791
- ])
792
-
793
- /** a header with the definitions Swift owns replaced by an import of its interface header. */
794
- export function withoutSwiftDeclarations(
795
- text: string,
796
- declared: ReadonlySet<string>,
797
- interfaceImport: string,
798
- ): string {
799
- const out: string[] = []
800
- let skipping: 'objc' | 'enum' | undefined
801
- let imported = false
802
- // clang refuses to enter a header inside an assume_nonnull region, so the
803
- // import goes above the region's start when the declaration sits inside it.
804
- let regionStart = -1
805
- for (const line of text.split('\n')) {
806
- if (skipping) {
807
- if (skipping === 'objc' ? /^@end\b/.test(line) : /^\s*};/.test(line))
808
- skipping = undefined
809
- continue
810
- }
811
- if (regionStart < 0 && /^NS_ASSUME_NONNULL_BEGIN\b/.test(line))
812
- regionStart = out.length
813
- const name =
814
- /^\s*(?:[A-Z_]\w*(?:\([^()\n]*\))?\s+)*@(?:protocol|interface)\s+(\w+)\s*(?=[:<{]|$)/.exec(
815
- line,
816
- )?.[1]
817
- // an @_cdecl function the native headers already declare keeps their prototype
818
- const external = /^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(.*\)[^;\n]*;\s*$/.exec(
819
- line,
820
- )?.[1]
821
- if (external && declared.has(external)) continue
822
- const enumeration =
823
- /^\s*typedef\s+(?:NS_ENUM|NS_OPTIONS|SWIFT_ENUM(?:_NAMED)?)\s*\(\s*\w+\s*,\s*(\w+)\b/.exec(
824
- line,
825
- )?.[1]
826
- const enumForward = objcEnumForward.exec(line)?.[1]
827
- const declaration = name ?? enumeration ?? enumForward
828
- if (declaration && declared.has(declaration)) {
829
- skipping = name ? 'objc' : enumeration && !line.includes('};') ? 'enum' : undefined
830
- // generated Swift annotations belong to the declaration being removed.
831
- while (
832
- /^(?:SWIFT_[A-Z_]+|(?:NS|CF)_SWIFT_NAME)(?:\(.*\))?\s*$/.test(out.at(-1) ?? '')
833
- )
834
- out.pop()
835
- if (!imported)
836
- out.splice(regionStart < 0 ? out.length : regionStart, 0, interfaceImport)
837
- imported = true
838
- continue
839
- }
840
- out.push(line)
841
- }
842
- return out.join('\n')
843
- }
844
-
845
- /** the wasm SDK a module root compiles with: a distribution's manifest names
846
- * it, a source checkout's toolchain.json pins it. */
847
- export function swiftModuleSdk(root: string): SwiftWasmSdk {
848
- const pin = swiftDistributionAt(root) ?? swiftSourceSdk(root)
849
- return {
850
- wasmSdkId: pin.wasmSdkId,
851
- wasmSdkUrl: pin.wasmSdkUrl,
852
- wasmSdkChecksum: pin.wasmSdkChecksum,
853
- }
854
- }
855
-
856
- /** swiftpm's sdk option for a compile against `moduleRoot`: the installed
857
- * sdk seen through the module root's shared framework headers. */
858
- export function swiftCompileSdkOptions(
859
- moduleRoot: string,
860
- toolchainBin: string,
861
- ): string[] {
862
- return swiftSharedSdkViewOptions(
863
- moduleRoot,
864
- swiftDistributionAt(moduleRoot) !== null,
865
- toolchainBin,
866
- swiftModuleSdk(moduleRoot).wasmSdkId,
867
- )
868
- }
869
-
870
530
  /** consumer targets send the selectors iOS names, as the SDK's own targets do. */
871
531
  function swiftObjCSelectorOptions(moduleRoot: string): string[] {
872
532
  const distribution = swiftDistributionAt(moduleRoot)
@@ -900,133 +560,6 @@ function swiftObjCSelectorOptions(moduleRoot: string): string[] {
900
560
  return ['-Xswiftc', '-Xllvm', '-Xswiftc', `-peach-objc-selector-map=${map}`]
901
561
  }
902
562
 
903
- // toolchain.json is an input for its wasm sdk checksum: the sdk's icu blob,
904
- // which the host fills into every artifact, is part of what the address names.
905
- // distribution producers are inputs so repaired builds get a fresh immutable id.
906
- // a distribution's manifest names every file it ships by digest.
907
- export function swiftModuleInputFiles(root: string): string[] {
908
- if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST]
909
- const files: string[] = [
910
- ...swiftSharedSdkInputFiles(root),
911
- '../peachsim/src/swift-shared-sdk.ts',
912
- '../peachsim/src/swift-runtime-products.ts',
913
- '../peachsim/src/swiftRuntimeProductContract.ts',
914
- '../peachsim/src/swiftTargetContract.ts',
915
- '../peachsim/src/swift-darwin-records.ts',
916
- '../peachsim/src/swift-uniform-type-constants.ts',
917
- '../peach-engine/native/core/input/control_tracking.h',
918
- '../../scripts/generate/swift-sdk-module/darwin-mach.json',
919
- '../../scripts/generate/swift-sdk-module/darwin-socketvar.json',
920
- '../../scripts/ops/swift-distribution-publish.ts',
921
- '../../src/helpers/mapLimit.ts',
922
- 'Package.swift',
923
- 'scripts/contrast-app-Package.swift',
924
- 'scripts/build-distribution.ts',
925
- 'scripts/runtime-product.ts',
926
- 'scripts/runtime-product-scopes.ts',
927
- 'scripts/distribution-runtime-products.ts',
928
- 'scripts/build-helpers.ts',
929
- 'scripts/build-cache.ts',
930
- 'scripts/build-cache-launcher.ts',
931
- 'scripts/distribution-clang.ts',
932
- 'runtime/UniformTypeIdentifiersConstants.m',
933
- 'Sources/libxml2/include/module.modulemap',
934
- 'Sources/libxml2/COPYING',
935
- 'scripts/build-distribution-plugins.sh',
936
- 'scripts/build-distribution-plugins-docker.sh',
937
- 'scripts/build-preview-plugin.sh',
938
- 'toolchain.json',
939
- ]
940
- const walk = (dir: string) => {
941
- for (const entry of readdirSync(path.join(root, dir), {
942
- withFileTypes: true,
943
- })) {
944
- const relative = `${dir}/${entry.name}`
945
- if (entry.isDirectory()) walk(relative)
946
- else if (
947
- /\.(swift|swiftinterface|swiftoverlay|c|cpp|h|inc|m|mm|modulemap|apinotes|json)$/.test(
948
- entry.name,
949
- )
950
- )
951
- files.push(relative)
952
- }
953
- }
954
- walk('Sources')
955
- walk('cross-import-overlays')
956
- // the iOS simulator standard library objective-c stand-ins import against
957
- walk('ios-simulator-stdlib')
958
- return files.sort()
959
- }
960
-
961
- // the host macro plugins build side by side and load explicitly for every
962
- // app compile. their source inputs also participate in artifact identity.
963
- /** the host macro plugin libraries a module root compiles with, and whether a
964
- * checkout's must be rebuilt (scripts/build-preview-plugin.sh) first. */
965
- export function swiftMacroPlugins(
966
- moduleRoot: string,
967
- dir = path.join(moduleRoot, '.build/host/RnxPreviewMacros'),
968
- ): {
969
- libraries: string[]
970
- executables: string[]
971
- stale: boolean
972
- } {
973
- const distribution = swiftDistributionAt(moduleRoot)
974
- if (distribution) {
975
- const view = swiftDistributionCompileView(moduleRoot, distribution)
976
- return {
977
- libraries: distribution.plugins
978
- .filter((plugin) => path.basename(plugin) !== 'ExpoModulesMacros')
979
- .map((plugin) => path.join(view, plugin)),
980
- executables: distribution.plugins
981
- .filter((plugin) => path.basename(plugin) === 'ExpoModulesMacros')
982
- .map((plugin) => path.join(view, plugin)),
983
- stale: false,
984
- }
985
- }
986
- const release = JSON.parse(
987
- readFileSync(path.join(moduleRoot, 'toolchain.json'), 'utf8'),
988
- ).release
989
- const compilerStamp = path.join(dir, 'compiler-release')
990
- const pluginScript = path.join(moduleRoot, 'scripts/build-preview-plugin.sh')
991
- const expoPlugin = path.join(dir, 'ExpoModulesMacros')
992
- // linux names a plugin's module from lib<Module>.so
993
- const ext = process.platform === 'darwin' ? 'dylib' : 'so'
994
- const plugins = [
995
- {
996
- library: path.join(dir, `libRnxPreviewMacros.${ext}`),
997
- sources: [path.join(moduleRoot, 'Sources/RnxPreviewMacros/PreviewMacro.swift')],
998
- },
999
- {
1000
- library: path.join(dir, `libFoundationMacros.${ext}`),
1001
- sources: [
1002
- path.join(moduleRoot, 'Sources/FoundationMacros/PredicateMacro.swift'),
1003
- path.join(moduleRoot, 'Sources/SwiftMacroSupport/PredicateExpression.swift'),
1004
- ],
1005
- },
1006
- {
1007
- library: path.join(dir, `libTipKitMacros.${ext}`),
1008
- sources: [
1009
- path.join(moduleRoot, 'Sources/TipKitMacros/TipKitMacros.swift'),
1010
- path.join(moduleRoot, 'Sources/SwiftMacroSupport/PredicateExpression.swift'),
1011
- ],
1012
- },
1013
- ]
1014
- return {
1015
- libraries: plugins.map(({ library }) => library),
1016
- executables: [expoPlugin],
1017
- stale:
1018
- !existsSync(compilerStamp) ||
1019
- !existsSync(expoPlugin) ||
1020
- statSync(pluginScript).mtimeMs > statSync(expoPlugin).mtimeMs ||
1021
- readFileSync(compilerStamp, 'utf8').trim() !== release ||
1022
- plugins.some(
1023
- ({ library, sources }) =>
1024
- !existsSync(library) ||
1025
- sources.some((source) => statSync(source).mtimeMs > statSync(library).mtimeMs),
1026
- ),
1027
- }
1028
- }
1029
-
1030
563
  export async function ensureMacroPlugins(
1031
564
  moduleRoot: string,
1032
565
  toolchainBin: string,
@@ -1053,186 +586,6 @@ export async function ensureMacroPlugins(
1053
586
  return { libraries, executables }
1054
587
  }
1055
588
 
1056
- const linkedModuleDigests = new Map<string, { stamp: string; digest: Buffer }>()
1057
-
1058
- export function clearLinkedModuleDigests(root?: string): void {
1059
- if (root === undefined) linkedModuleDigests.clear()
1060
- else linkedModuleDigests.delete(root)
1061
- }
1062
-
1063
- // a clean git worktree shares the exact same source bytes as any other worktree
1064
- // on the same tree/blob OIDs. hashing the git OIDs avoids reading 14k+ files on
1065
- // every fresh worktree while still falling back to full reads on any dirty input.
1066
- function gitCleanModuleInputsKey(root: string, files: readonly string[]): string | null {
1067
- if (swiftDistributionAt(root)) return null
1068
- const top = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], {
1069
- encoding: 'utf8',
1070
- stdio: ['ignore', 'pipe', 'ignore'],
1071
- })
1072
- if (top.status !== 0) return null
1073
- const repoTop = top.stdout.trim()
1074
- if (!repoTop) return null
1075
- const realTop = realpathSync(repoTop)
1076
- const realRoot = realpathSync(root)
1077
- const collapsedDirs = [
1078
- path.join(realRoot, 'Sources'),
1079
- path.join(realRoot, 'cross-import-overlays'),
1080
- path.join(realRoot, 'ios-simulator-stdlib'),
1081
- realpathSync(path.resolve(realRoot, '../peachsim/sdk/ios')),
1082
- ]
1083
- const scoped = new Set<string>()
1084
- for (const dir of collapsedDirs) {
1085
- const rel = path.relative(realTop, dir).split(path.sep).join('/')
1086
- if (!rel || rel.startsWith('../')) return null
1087
- scoped.add(rel)
1088
- }
1089
- for (const file of files) {
1090
- const full = path.resolve(realRoot, file)
1091
- if (collapsedDirs.some((dir) => full.startsWith(dir + path.sep))) continue
1092
- const rel = path.relative(realTop, full).split(path.sep).join('/')
1093
- if (!rel || rel.startsWith('../')) return null
1094
- scoped.add(rel)
1095
- }
1096
- const paths = [...scoped].sort()
1097
- const status = spawnSync(
1098
- 'git',
1099
- [
1100
- '-C',
1101
- realTop,
1102
- 'status',
1103
- '--porcelain',
1104
- '--untracked-files=all',
1105
- '--ignored=matching',
1106
- '--',
1107
- ...paths,
1108
- ],
1109
- {
1110
- encoding: 'utf8',
1111
- stdio: ['ignore', 'pipe', 'ignore'],
1112
- maxBuffer: 16 * 1024 * 1024,
1113
- },
1114
- )
1115
- if (status.status !== 0 || status.stdout.trim().length > 0) return null
1116
- const oids = spawnSync(
1117
- 'git',
1118
- ['-C', realTop, 'rev-parse', ...paths.map((entry) => `HEAD:${entry}`)],
1119
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
1120
- )
1121
- if (oids.status !== 0) return null
1122
- const keyHash = createHash('sha256')
1123
- keyHash.update('git-module-digest/v1\n')
1124
- keyHash.update(oids.stdout)
1125
- keyHash.update('\n')
1126
- for (const file of files) keyHash.update(file).update('\n')
1127
- return keyHash.digest('hex')
1128
- }
1129
-
1130
- /** the digest of a module checkout's inputs: what an artifact address and a
1131
- * distribution's id name it by. */
1132
- export function swiftModuleDigest(root: string): Buffer {
1133
- const files = swiftModuleInputFiles(root)
1134
- const stampHash = createHash('sha256')
1135
- for (const file of files) {
1136
- const stat = statSync(path.join(root, file), { bigint: true })
1137
- stampHash.update(file)
1138
- stampHash.update(
1139
- `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}\n`,
1140
- )
1141
- }
1142
- const stamp = stampHash.digest('hex')
1143
- const cached = linkedModuleDigests.get(root)
1144
- if (cached?.stamp === stamp) return cached.digest
1145
- // a source checkout holds thousands of inputs, so a fresh bridge reuses the
1146
- // digest an earlier process recorded under the same stamp.
1147
- const digestDir = path.join(swiftCacheDir(), 'swift-module-digests')
1148
- const record = path.join(
1149
- digestDir,
1150
- `${createHash('sha256').update(root).digest('hex')}.json`,
1151
- )
1152
- const writeRecord = (target: string, body: string) => {
1153
- mkdirSync(path.dirname(target), { recursive: true })
1154
- const partial = `${target}.${process.pid}.${randomUUID()}`
1155
- writeFileSync(partial, body)
1156
- renameSync(partial, target)
1157
- }
1158
- if (existsSync(record)) {
1159
- const saved: unknown = JSON.parse(readFileSync(record, 'utf8'))
1160
- if (
1161
- saved &&
1162
- typeof saved === 'object' &&
1163
- Reflect.get(saved, 'stamp') === stamp &&
1164
- typeof Reflect.get(saved, 'digest') === 'string'
1165
- ) {
1166
- const digest = Buffer.from(String(Reflect.get(saved, 'digest')), 'hex')
1167
- linkedModuleDigests.set(root, { stamp, digest })
1168
- return digest
1169
- }
1170
- }
1171
- const gitKey = gitCleanModuleInputsKey(root, files)
1172
- const gitRecord = gitKey ? path.join(digestDir, `git-${gitKey}.json`) : null
1173
- if (gitRecord && existsSync(gitRecord)) {
1174
- const saved: unknown = JSON.parse(readFileSync(gitRecord, 'utf8'))
1175
- if (
1176
- saved &&
1177
- typeof saved === 'object' &&
1178
- typeof Reflect.get(saved, 'digest') === 'string'
1179
- ) {
1180
- const hex = String(Reflect.get(saved, 'digest'))
1181
- const digest = Buffer.from(hex, 'hex')
1182
- linkedModuleDigests.set(root, { stamp, digest })
1183
- writeRecord(record, JSON.stringify({ stamp, digest: hex }))
1184
- return digest
1185
- }
1186
- }
1187
- const hash = createHash('sha256')
1188
- for (const file of files) {
1189
- hash.update(createHash('sha256').update(file).digest())
1190
- hash.update(
1191
- createHash('sha256')
1192
- .update(readFileSync(path.join(root, file)))
1193
- .digest(),
1194
- )
1195
- }
1196
- const digest = hash.digest()
1197
- const hex = digest.toString('hex')
1198
- linkedModuleDigests.set(root, { stamp, digest })
1199
- writeRecord(record, JSON.stringify({ stamp, digest: hex }))
1200
- if (gitRecord) writeRecord(gitRecord, JSON.stringify({ digest: hex }))
1201
- return digest
1202
- }
1203
-
1204
- const compileSurfaces = new WeakMap<SwiftDistributionManifest, Buffer>()
1205
-
1206
- /**
1207
- * the digest of what a compile against a module root reads. a distribution's
1208
- * objects reach only a link, so distributions that differ in function bodies
1209
- * alone share every product compiled against either.
1210
- */
1211
- export function swiftCompileSurfaceDigest(root: string): Buffer {
1212
- const distribution = swiftDistributionAt(root)
1213
- if (!distribution) return swiftModuleDigest(root)
1214
- let digest = compileSurfaces.get(distribution)
1215
- if (!digest) {
1216
- digest = createHash('sha256')
1217
- .update(
1218
- JSON.stringify([
1219
- distribution.release,
1220
- distribution.wasmSdkId,
1221
- distribution.wasmSdkChecksum,
1222
- distribution.modules,
1223
- distribution.plugins,
1224
- distribution.link,
1225
- Object.entries(distribution.files)
1226
- .filter(([file]) => !file.startsWith('lib/'))
1227
- .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),
1228
- ]),
1229
- )
1230
- .digest()
1231
- compileSurfaces.set(distribution, digest)
1232
- }
1233
- return digest
1234
- }
1235
-
1236
589
  // optimized consumers can reference private symbols from an imported framework.
1237
590
  // source revisions need separate object trees, while app edits keep one warm tree.
1238
591
  export function swiftProjectBuildKey(moduleRoot: string, release: string): string {
@@ -1258,21 +611,71 @@ const SYSTEM_MODULE_LIBRARIES: Record<string, string> = {
1258
611
  const SYSTEM_MODULE_IMPORT =
1259
612
  /^\s*(?:#\s*(?:import|include)\s*<(sqlite3(?:ext)?\.h|bzlib\.h|zlib\.h)>|@import\s+(SQLite3)\b)/gm
1260
613
 
614
+ let lastPartition:
615
+ | {
616
+ manifest: string
617
+ resourcePaths: readonly string[] | undefined
618
+ targets: SwiftPackageTarget[]
619
+ }
620
+ | undefined
621
+
622
+ function sameStringList(
623
+ left: readonly string[] | undefined,
624
+ right: readonly string[] | undefined,
625
+ ): boolean {
626
+ if (left === right) return true
627
+ if (!left || !right || left.length !== right.length) return false
628
+ for (let i = 0; i < left.length; i++) if (left[i] !== right[i]) return false
629
+ return true
630
+ }
631
+
632
+ function cachedSwiftPackagePartition(
633
+ manifest: string,
634
+ resourcePaths: readonly string[] | undefined,
635
+ ): SwiftPackageTarget[] {
636
+ if (
637
+ lastPartition &&
638
+ lastPartition.manifest === manifest &&
639
+ sameStringList(lastPartition.resourcePaths, resourcePaths)
640
+ )
641
+ return lastPartition.targets
642
+ const targets = swiftPackagePartition(manifest, resourcePaths)
643
+ lastPartition = {
644
+ manifest,
645
+ resourcePaths: resourcePaths ? [...resourcePaths] : undefined,
646
+ targets,
647
+ }
648
+ return targets
649
+ }
650
+
1261
651
  export function compileTargets(input: SwiftCompileInput): SwiftPackageTarget[] {
1262
652
  const manifest = input.files['Package.swift']
1263
653
  if (manifest === undefined) return []
1264
- const targets = swiftPackagePartition(manifest, input.resourcePaths)
654
+ const targets = cachedSwiftPackagePartition(manifest, input.resourcePaths)
1265
655
  const owners = [...targets].sort((left, right) => right.path.length - left.path.length)
1266
656
  const autolinks = new Map<string, Set<string>>()
1267
657
  for (const [file, contents] of Object.entries(input.files)) {
1268
658
  if (!/\.(c|cc|cpp|cxx|h|hh|hpp|m|mm)$/.test(file)) continue
659
+ if (
660
+ !contents.includes('sqlite3') &&
661
+ !contents.includes('bzlib.h') &&
662
+ !contents.includes('zlib.h') &&
663
+ !contents.includes('SQLite3')
664
+ )
665
+ continue
666
+ let owner: SwiftPackageTarget | undefined
1269
667
  for (const match of contents.matchAll(SYSTEM_MODULE_IMPORT)) {
1270
- const owner = owners.find(
668
+ owner ??= owners.find(
1271
669
  (target) => target.path === '.' || file.startsWith(`${target.path}/`),
1272
670
  )
1273
671
  const library = SYSTEM_MODULE_LIBRARIES[match[1] ?? match[2] ?? '']
1274
672
  if (!owner || !library) break
1275
- autolinks.set(owner.name, new Set([...(autolinks.get(owner.name) ?? []), library]))
673
+ let libs = autolinks.get(owner.name)
674
+ if (!libs) {
675
+ libs = new Set()
676
+ autolinks.set(owner.name, libs)
677
+ }
678
+ libs.add(library)
1276
679
  }
1277
680
  }
1278
681
  return targets.map((target) => {
@@ -1388,274 +791,6 @@ export function swiftOptionalFramework(name: string): boolean {
1388
791
  return OPTIONAL_FRAMEWORKS.has(name)
1389
792
  }
1390
793
 
1391
- // an import may carry attributes (`@_exported`, `@preconcurrency`) and a
1392
- // declaration kind (`import struct Nuke.ImageRequest`).
1393
- const SWIFT_IMPORT =
1394
- /^\s*(?:@\w+(?:\([^)]*\))?\s+|(?:public|package|internal|fileprivate|private)\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/
1395
-
1396
- // three-valued (kleene) logic shared by the swift and c condition
1397
- // evaluators: an undecided operand only decides when the other forces the
1398
- // outcome, so false && undefined is false and true || undefined is true.
1399
- const kleeneNot = (value: boolean | undefined): boolean | undefined =>
1400
- value === undefined ? undefined : !value
1401
- const kleeneAnd = (
1402
- left: boolean | undefined,
1403
- right: boolean | undefined,
1404
- ): boolean | undefined =>
1405
- left === false || right === false
1406
- ? false
1407
- : left === true && right === true
1408
- ? true
1409
- : undefined
1410
- const kleeneOr = (
1411
- left: boolean | undefined,
1412
- right: boolean | undefined,
1413
- ): boolean | undefined =>
1414
- left === true || right === true
1415
- ? true
1416
- : left === false && right === false
1417
- ? false
1418
- : undefined
1419
-
1420
- // a compilation condition as the wasm compile sees it after the source
1421
- // rewrite below: `os(iOS)` holds, other platforms (WASI too) do not,
1422
- // `canImport` holds for an available module. what the scan cannot know
1423
- // (custom flags, swift versions, features) is undefined, three-valued
1424
- // through `!`, `&&` and `||`.
1425
- const NON_IOS_MODULES = new Set(['FoundationNetworking', 'WASILibc'])
1426
-
1427
- function swiftCondition(
1428
- text: string,
1429
- available?: ReadonlySet<string>,
1430
- defines?: ReadonlySet<string>,
1431
- ): boolean | undefined {
1432
- const tokens = text.match(/\w+\s*\([^()]*\)|&&|\|\||!|\(|\)|\w+/g) ?? []
1433
- let index = 0
1434
- const atom = (): boolean | undefined => {
1435
- const token = tokens[index++]
1436
- if (token === '!') return kleeneNot(atom())
1437
- if (token === '(') {
1438
- const value = either()
1439
- index++
1440
- return value
1441
- }
1442
- if (token === 'true') return true
1443
- if (token === 'false') return false
1444
- // with the target's full -D set known, swift reads any other name as false.
1445
- if (defines && /^[A-Za-z_]\w*$/.test(token ?? '')) return defines.has(token!)
1446
- const call = /^(\w+)\s*\(\s*([^,()]*?)\s*(?:,[^()]*)?\)$/.exec(token ?? '')
1447
- if (!call) return undefined
1448
- const [, name, argument] = call
1449
- if (name === 'os') return argument === 'iOS'
1450
- if (name === 'canImport')
1451
- return !NON_IOS_MODULES.has(argument!) && available?.has(argument!)
1452
- if (name === 'targetEnvironment') return argument === 'simulator'
1453
- if (name === 'arch') return argument === 'wasm64' || argument === 'arm64'
1454
- return undefined
1455
- }
1456
- const both = (): boolean | undefined => {
1457
- let value = atom()
1458
- while (tokens[index] === '&&') {
1459
- index++
1460
- value = kleeneAnd(value, atom())
1461
- }
1462
- return value
1463
- }
1464
- const either = (): boolean | undefined => {
1465
- let value = both()
1466
- while (tokens[index] === '||') {
1467
- index++
1468
- value = kleeneOr(value, both())
1469
- }
1470
- return value
1471
- }
1472
- return either()
1473
- }
1474
-
1475
- // each line's branch state under the app's wasm compilation conditions.
1476
- // directives themselves are not executable source. the scan reads code, never
1477
- // content: an `import` or directive inside a string literal or comment is
1478
- // template text, not source (a dependency's code template once reported its
1479
- // `import Cocoa` line as a missing module).
1480
- function* swiftConditionalLines(
1481
- contents: string,
1482
- available?: ReadonlySet<string>,
1483
- defines?: ReadonlySet<string>,
1484
- ): Generator<{ line: string; active: boolean | undefined }> {
1485
- // per open `#if`: whether its current branch is active, and whether an
1486
- // earlier branch was taken (or may have been)
1487
- const frames: { active: boolean | undefined; taken: boolean | undefined }[] = []
1488
- for (const line of swiftCodeMask(contents).split('\n')) {
1489
- const directive = /^\s*#(if|elseif|else|endif)\b(.*)$/.exec(line)
1490
- if (directive) {
1491
- const [, kind, rest] = directive
1492
- const condition = (rest ?? '').replace(/\/\/.*$/, '').trim()
1493
- if (kind === 'if') {
1494
- const active = swiftCondition(condition, available, defines)
1495
- frames.push({ active, taken: active })
1496
- } else if (kind === 'endif') frames.pop()
1497
- else if (frames.length > 0) {
1498
- const frame = frames[frames.length - 1]!
1499
- const holds =
1500
- kind === 'else' ? true : swiftCondition(condition, available, defines)
1501
- frame.active =
1502
- frame.taken === true
1503
- ? false
1504
- : frame.taken === false
1505
- ? holds
1506
- : holds && undefined
1507
- frame.taken =
1508
- frame.taken === true || holds === true
1509
- ? true
1510
- : frame.taken === false
1511
- ? holds
1512
- : undefined
1513
- }
1514
- yield { line, active: false }
1515
- continue
1516
- }
1517
- yield {
1518
- line,
1519
- active: frames.some((frame) => frame.active === false)
1520
- ? false
1521
- : frames.every((frame) => frame.active === true)
1522
- ? true
1523
- : undefined,
1524
- }
1525
- }
1526
- }
1527
-
1528
- /**
1529
- * the modules a source imports, in order. with `available`, only imports the
1530
- * wasm compile certainly reaches: those outside every `#if`, or in a branch
1531
- * whose condition holds there, `os(iOS)` included since the compile rewrites
1532
- * it to true. a branch the scan cannot decide may compile out, so its
1533
- * imports stay out of the list.
1534
- */
1535
- export function swiftImportNames(
1536
- contents: string,
1537
- available?: ReadonlySet<string>,
1538
- ): string[] {
1539
- const names: string[] = []
1540
- for (const { line, active } of swiftConditionalLines(contents, available)) {
1541
- if (available && active !== true) continue
1542
- const name = SWIFT_IMPORT.exec(line)?.[1]
1543
- if (name) names.push(name)
1544
- }
1545
- return names
1546
- }
1547
-
1548
- /**
1549
- * the modules peach itself provides at `moduleRoot`: a distribution lists
1550
- * them, a checkout's manifest declares them as targets.
1551
- */
1552
- export function swiftPeachModules(moduleRoot: string): string[] {
1553
- const distribution = swiftDistributionAt(moduleRoot)
1554
- return distribution
1555
- ? distribution.modules
1556
- : swiftManifestDeclarations(
1557
- readFileSync(path.join(moduleRoot, 'Package.swift'), 'utf8'),
1558
- )
1559
- .filter((target) => !target.executable && !target.path.startsWith('fixtures/'))
1560
- .map((target) => target.name)
1561
- }
1562
-
1563
- const sdkPaths = new Map<
1564
- string,
1565
- {
1566
- sysroot: string
1567
- darwin: string
1568
- resources: string
1569
- frameworks: string[]
1570
- cFlags: string[]
1571
- }
1572
- >()
1573
-
1574
- /** the wasm SDK's sysroot, swift resource directory, and clang intake.
1575
- * raw swiftc does not read the toolset, so stand-in compiles pass cFlags. */
1576
- export function swiftSdkPaths(
1577
- moduleRoot: string,
1578
- toolchainBin: string,
1579
- options = swiftCompileSdkOptions(moduleRoot, toolchainBin),
1580
- ): {
1581
- sysroot: string
1582
- darwin: string
1583
- resources: string
1584
- frameworks: string[]
1585
- cFlags: string[]
1586
- } {
1587
- const sdk = swiftModuleSdk(moduleRoot).wasmSdkId
1588
- const key = JSON.stringify([toolchainBin, sdk, options])
1589
- const cached = sdkPaths.get(key)
1590
- if (cached) return cached
1591
- const configuration = execFileSync(
1592
- path.join(toolchainBin, 'swift'),
1593
- ['sdk', 'configure', ...options, '--show-configuration', sdk, SWIFT_WASM_TRIPLE],
1594
- { encoding: 'utf8', env: swiftEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] },
1595
- )
1596
- const field = (name: string) => {
1597
- const value = new RegExp(`^${name}:\\s*(.+)$`, 'm').exec(configuration)?.[1]?.trim()
1598
- if (!value) throw new Error(`swift sdk ${sdk} reports no ${name}`)
1599
- return value
1600
- }
1601
- const sysroot = field('sdkRootPath')
1602
- // clang flags from the toolset's swift driver. -fwasm-exceptions is omitted:
1603
- // it selects the wasm exception model and aborts unless -Xllvm
1604
- // -wasm-enable-eh is also passed, and symbolgraph-extract has no -Xllvm.
1605
- const cFlags: string[] = []
1606
- const frameworks: string[] = []
1607
- const configuredToolsets = field('toolsetPaths')
1608
- if (configuredToolsets !== 'not set') {
1609
- const toolsets: unknown = JSON.parse(configuredToolsets)
1610
- if (!Array.isArray(toolsets) || !toolsets.every((value) => typeof value === 'string'))
1611
- throw new Error(`swift sdk ${sdk} reports invalid toolset paths`)
1612
- for (const toolset of toolsets) {
1613
- const config: unknown = JSON.parse(readFileSync(toolset, 'utf8'))
1614
- if (!config || typeof config !== 'object' || !('swiftCompiler' in config)) continue
1615
- const compiler = config.swiftCompiler
1616
- if (!compiler || typeof compiler !== 'object' || !('extraCLIOptions' in compiler))
1617
- continue
1618
- const options = compiler.extraCLIOptions
1619
- if (!Array.isArray(options) || !options.every((value) => typeof value === 'string'))
1620
- throw new Error(
1621
- `swift sdk ${sdk} has invalid swift compiler options in ${toolset}`,
1622
- )
1623
- for (let index = 0; index < options.length; index++) {
1624
- if (options[index] === '-Xcc' && typeof options[index + 1] === 'string') {
1625
- const flag = options[index + 1]
1626
- if (flag !== '-fwasm-exceptions') cFlags.push(flag)
1627
- if (
1628
- flag === '-iframeworkwithsysroot' &&
1629
- options[index + 2] === '-Xcc' &&
1630
- typeof options[index + 3] === 'string'
1631
- ) {
1632
- cFlags.push(options[index + 3])
1633
- frameworks.push(path.join(sysroot, options[index + 3]))
1634
- index += 3
1635
- continue
1636
- }
1637
- index += 1
1638
- continue
1639
- }
1640
- const option = options[index]
1641
- if (option.startsWith('-iframework') || option.startsWith('-F'))
1642
- throw new Error(
1643
- `swift sdk ${sdk} has an unsupported framework search option ${option}`,
1644
- )
1645
- }
1646
- }
1647
- }
1648
- const paths = {
1649
- sysroot,
1650
- darwin: path.join(sysroot, 'darwin'),
1651
- resources: field('swiftResourcesPath'),
1652
- frameworks,
1653
- cFlags,
1654
- }
1655
- sdkPaths.set(key, paths)
1656
- return paths
1657
- }
1658
-
1659
794
  const availableModules = new Map<string, Set<string>>()
1660
795
 
1661
796
  // only frameworks replaced by a Swift module lose their clang submodules.
@@ -2006,6 +1141,25 @@ export function swiftTargetDependencies(
2006
1141
  const entriesByPrefix = new Map<string, [string, string][]>(
2007
1142
  targets.map(({ path }) => [path === '.' ? '' : `${path}/`, []]),
2008
1143
  )
1144
+ const targetByPrefix = new Map<string, string>()
1145
+ for (const target of targets) {
1146
+ if (target.path !== '.') targetByPrefix.set(`${target.path}/`, target.name)
1147
+ }
1148
+ const ownedByOtherTarget = (
1149
+ file: string,
1150
+ ownerName: string,
1151
+ fromOffset = 0,
1152
+ ): boolean => {
1153
+ for (
1154
+ let end = file.indexOf('/', fromOffset);
1155
+ end !== -1;
1156
+ end = file.indexOf('/', end + 1)
1157
+ ) {
1158
+ const candidate = targetByPrefix.get(file.slice(0, end + 1))
1159
+ if (candidate !== undefined && candidate !== ownerName) return true
1160
+ }
1161
+ return false
1162
+ }
2009
1163
  for (const entry of Object.entries(files)) {
2010
1164
  const [file] = entry
2011
1165
  entriesByPrefix.get('')?.push(entry)
@@ -2015,17 +1169,13 @@ export function swiftTargetDependencies(
2015
1169
  const siblings = new Map<string, string[]>()
2016
1170
  for (const target of targets) {
2017
1171
  const prefix = target.path === '.' ? '' : `${target.path}/`
2018
- const ownsHeader = (header: string) =>
2019
- [`${prefix}${header}`, `${prefix}include/${header}`].some(
2020
- (file) =>
2021
- Object.hasOwn(files, file) &&
2022
- !targets.some(
2023
- (candidate) =>
2024
- candidate.name !== target.name &&
2025
- candidate.path !== '.' &&
2026
- file.startsWith(`${candidate.path}/`),
2027
- ),
2028
- )
1172
+ const ownsHeader = (header: string) => {
1173
+ const direct = `${prefix}${header}`
1174
+ if (Object.hasOwn(files, direct) && !ownedByOtherTarget(direct, target.name))
1175
+ return true
1176
+ const included = `${prefix}include/${header}`
1177
+ return Object.hasOwn(files, included) && !ownedByOtherTarget(included, target.name)
1178
+ }
2029
1179
  const deps = new Set(
2030
1180
  (target.dependencies ?? []).flatMap((dependency) =>
2031
1181
  (dependency.kind === 'target' &&
@@ -2038,16 +1188,7 @@ export function swiftTargetDependencies(
2038
1188
  : [],
2039
1189
  ),
2040
1190
  )
2041
- const nested =
2042
- target.sources === undefined
2043
- ? targets.flatMap((candidate) =>
2044
- candidate.name !== target.name &&
2045
- candidate.path !== '.' &&
2046
- candidate.path.startsWith(prefix)
2047
- ? [`${candidate.path}/`]
2048
- : [],
2049
- )
2050
- : []
1191
+ const checkNested = target.sources === undefined
2051
1192
  for (const [file, contents] of entriesByPrefix.get(prefix) ?? []) {
2052
1193
  if (file === 'Package.swift') continue
2053
1194
  const relative = file.slice(prefix.length)
@@ -2065,7 +1206,7 @@ export function swiftTargetDependencies(
2065
1206
  )
2066
1207
  )
2067
1208
  continue
2068
- if (nested.some((path) => file.startsWith(path))) continue
1209
+ if (checkNested && ownedByOtherTarget(file, target.name, prefix.length)) continue
2069
1210
  const imports = file.endsWith('.swift')
2070
1211
  ? swiftImportNames(contents)
2071
1212
  : SWIFT_NATIVE_SOURCE_EXTENSIONS.some((extension) => file.endsWith(extension))
@@ -2107,62 +1248,6 @@ const GAME_REACH: Record<string, string[]> = {
2107
1248
  SpriteKit: ['SpriteKit', 'PeachBox2D', 'simd', 'GLKit'],
2108
1249
  SceneKit: ['SceneKit'],
2109
1250
  }
2110
- // the guest implements native Foundation's exports in several modules.
2111
- export const FOUNDATION_IMPLICIT_MODULES = [
2112
- 'PeachObjC',
2113
- 'Dispatch',
2114
- 'FoundationNetworking',
2115
- 'PeachFoundationCombine',
2116
- 'Darwin',
2117
- ]
2118
- const FRAMEWORK_COMPANION_IMPORT =
2119
- /^[ \t]*((?:(?:@\w+(?:\([^)]*\))?|public|package|internal|fileprivate|private)[ \t]+)*)import[ \t]+(Foundation|UIKit|SwiftUI|Photos|CoreData|SystemConfiguration|Dispatch)[ \t]*;?[ \t]*$/
2120
-
2121
- export function withFrameworkCompanionImports(source: string): string {
2122
- const original = source.split('\n')
2123
- const imports: string[] = []
2124
- let hasCompanions = false
2125
- for (const [index, line] of swiftCodeMask(source).split('\n').entries()) {
2126
- const conditional = /#(?:(?:if|elseif)\b.*|(?:else|endif)\b)/.exec(line)
2127
- if (conditional) {
2128
- const start = conditional.index
2129
- imports.push(original[index]!.slice(start, start + conditional[0].length))
2130
- continue
2131
- }
2132
- const matched = FRAMEWORK_COMPANION_IMPORT.exec(line.trimEnd())
2133
- if (!matched) continue
2134
- const [, attributes = '', framework] = matched
2135
- const modifiers: string[] =
2136
- attributes.match(
2137
- /@(?:preconcurrency|_exported|_implementationOnly)\b|\b(?:public|package|internal|fileprivate|private)\b/g,
2138
- ) ?? []
2139
- const preconcurrency = modifiers.includes('@preconcurrency')
2140
- const modules =
2141
- framework === 'SystemConfiguration'
2142
- ? ['Dispatch', 'Darwin']
2143
- : framework === 'Dispatch'
2144
- ? ['PeachFoundationCombine']
2145
- : preconcurrency
2146
- ? ['CoreFoundation', 'ObjectiveC', ...FOUNDATION_IMPLICIT_MODULES]
2147
- : FOUNDATION_IMPLICIT_MODULES
2148
- const prefix = modifiers.length ? modifiers.join(' ') + ' ' : ''
2149
- imports.push(...modules.map((module) => `${prefix}import ${module}`))
2150
- if (framework === 'Foundation' && modifiers.includes('public'))
2151
- imports.push(
2152
- '@_exported public import protocol Combine.ObservableObject',
2153
- '@_exported public import struct Combine.Published',
2154
- )
2155
- if (framework === 'CoreData')
2156
- imports.push(
2157
- `${prefix}import protocol Combine.ObservableObject`,
2158
- `${prefix}import struct Combine.Published`,
2159
- )
2160
- hasCompanions = true
2161
- }
2162
- if (!hasCompanions) return source
2163
- // mirror conditional imports without shifting the original source locations.
2164
- return `${source}${source.endsWith('\n') ? '' : '\n'}#if canImport(PeachObjC)\n${imports.join('\n')}\n#endif\n`
2165
- }
2166
1251
  const ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"'
2167
1252
 
2168
1253
  // the executable link lines the template path and every emitted executable
@@ -2213,6 +1298,12 @@ export function swiftArtifactHash(
2213
1298
  .digest('hex')
2214
1299
  }
2215
1300
 
1301
+ function sha256Digest(value: string | Buffer): Uint8Array {
1302
+ if (typeof Bun !== 'undefined')
1303
+ return new Bun.CryptoHasher('sha256').update(value).digest()
1304
+ return createHash('sha256').update(value).digest()
1305
+ }
1306
+
2216
1307
  function swiftCompileInputHash(input: SwiftCompileInput, release: string) {
2217
1308
  const hash = createHash('sha256')
2218
1309
  hash.update(`swift-compile\n${release}\n`)
@@ -2223,36 +1314,28 @@ function swiftCompileInputHash(input: SwiftCompileInput, release: string) {
2223
1314
  if (input.optimize) hash.update('optimize\n')
2224
1315
  if (input.unoptimized) hash.update('unoptimized\n')
2225
1316
  for (const file of Object.keys(input.files).sort()) {
2226
- hash.update(createHash('sha256').update(file).digest())
2227
- hash.update(createHash('sha256').update(input.files[file]).digest())
1317
+ hash.update(sha256Digest(file))
1318
+ hash.update(sha256Digest(input.files[file]))
2228
1319
  }
2229
1320
  for (const file of Object.keys(input.metalSources ?? {}).sort()) {
2230
1321
  hash.update('metal-source\n')
2231
- hash.update(createHash('sha256').update(file).digest())
2232
- hash.update(
2233
- createHash('sha256')
2234
- .update(input.metalSources?.[file] ?? '')
2235
- .digest(),
2236
- )
1322
+ hash.update(sha256Digest(file))
1323
+ hash.update(sha256Digest(input.metalSources?.[file] ?? ''))
2237
1324
  }
2238
1325
  for (const base of Object.keys(input.resources ?? {}).sort()) {
2239
- hash.update(createHash('sha256').update(base).digest())
2240
- hash.update(
2241
- createHash('sha256')
2242
- .update(input.resources?.[base] ?? '')
2243
- .digest(),
2244
- )
1326
+ hash.update(sha256Digest(base))
1327
+ hash.update(sha256Digest(input.resources?.[base] ?? ''))
2245
1328
  }
2246
1329
  for (const name of Object.keys(input.images ?? {}).sort()) {
2247
1330
  const image = input.images?.[name]
2248
1331
  if (!image) continue
2249
- hash.update(createHash('sha256').update(name).digest())
2250
- hash.update(createHash('sha256').update(image.file).digest())
2251
- hash.update(createHash('sha256').update(image.data).digest())
1332
+ hash.update(sha256Digest(name))
1333
+ hash.update(sha256Digest(image.file))
1334
+ hash.update(sha256Digest(image.data))
2252
1335
  }
2253
1336
  for (const file of [...new Set(input.resourcePaths ?? [])].sort()) {
2254
1337
  hash.update('resource-path\n')
2255
- hash.update(createHash('sha256').update(file).digest())
1338
+ hash.update(sha256Digest(file))
2256
1339
  }
2257
1340
  hash.update(
2258
1341
  JSON.stringify(
@@ -2270,19 +1353,15 @@ function swiftCompileInputHash(input: SwiftCompileInput, release: string) {
2270
1353
  hash.update(`default-localization\n${input.defaultLocalization}\n`)
2271
1354
  for (const file of Object.keys(input.packageFiles ?? {}).sort()) {
2272
1355
  hash.update(`package-file\0${file}\0`)
2273
- hash.update(createHash('sha256').update(input.packageFiles![file]!).digest())
1356
+ hash.update(sha256Digest(input.packageFiles![file]!))
2274
1357
  }
2275
1358
  for (const file of Object.keys(input.projectFiles ?? {}).sort()) {
2276
1359
  hash.update(`project-file\0${file}\0`)
2277
- hash.update(createHash('sha256').update(input.projectFiles![file]!).digest())
1360
+ hash.update(sha256Digest(input.projectFiles![file]!))
2278
1361
  }
2279
1362
  for (const target of Object.keys(input.libraries ?? {}).sort()) {
2280
1363
  hash.update(`library\n${target}\n`)
2281
- hash.update(
2282
- createHash('sha256')
2283
- .update(input.libraries?.[target] ?? '')
2284
- .digest(),
2285
- )
1364
+ hash.update(sha256Digest(input.libraries?.[target] ?? ''))
2286
1365
  }
2287
1366
  for (const [name, bytes] of Object.entries(input.binaryModules ?? {}).sort())
2288
1367
  hash.update(`binary-module\0${name}\0${bytes}\0`)
@@ -3470,468 +2549,6 @@ export function lowerAVAssetURLCluster(source: string): string {
3470
2549
  return out
3471
2550
  }
3472
2551
 
3473
- // one compile masks each source in several scans; the cache holds a bounded
3474
- // number of characters and forgets everything when full.
3475
- const codeMasks = new Map<string, string>()
3476
- let codeMaskChars = 0
3477
- const CODE_MASK_CACHE_CHARS = 256 * 1024 * 1024
3478
-
3479
- export function swiftCodeMask(source: string): string {
3480
- const cached = codeMasks.get(source)
3481
- if (cached !== undefined) return cached
3482
- const masked = maskSwiftCode(source)
3483
- if (codeMaskChars + source.length > CODE_MASK_CACHE_CHARS) {
3484
- codeMasks.clear()
3485
- codeMaskChars = 0
3486
- }
3487
- codeMasks.set(source, masked)
3488
- codeMaskChars += source.length
3489
- return masked
3490
- }
3491
-
3492
- function maskSwiftCode(source: string): string {
3493
- const chars = source.split('')
3494
- const blank = (from: number, to: number): void => {
3495
- for (let i = Math.max(0, from); i < Math.min(to, chars.length); i++)
3496
- if (chars[i] !== '\n') chars[i] = ' '
3497
- }
3498
- const hashesAt = (at: number): number => {
3499
- let end = at
3500
- while (source[end] === '#') end++
3501
- return end - at
3502
- }
3503
- const scanString = (quote: number, hashes: number): number => {
3504
- const multiline = source.startsWith('"""', quote)
3505
- let i = quote + (multiline ? 3 : 1)
3506
- const keep: [number, number][] = []
3507
- const quoteEnd = (at: number): boolean => {
3508
- const mark = multiline ? '"""' : '"'
3509
- return (
3510
- source.startsWith(mark, at) &&
3511
- source.startsWith('#'.repeat(hashes), at + mark.length)
3512
- )
3513
- }
3514
- while (i < chars.length) {
3515
- if (source[i] === '\\' && source.startsWith('#'.repeat(hashes), i + 1)) {
3516
- const escaped = i + 1 + hashes
3517
- if (source[escaped] === '(') {
3518
- const codeStart = escaped + 1
3519
- const codeEnd = scanCode(codeStart, true)
3520
- keep.push([codeStart, codeEnd])
3521
- i = codeEnd + 1
3522
- } else {
3523
- i = escaped + 1
3524
- }
3525
- continue
3526
- }
3527
- if (quoteEnd(i)) {
3528
- const close = i + (multiline ? 3 : 1) + hashes
3529
- let cursor = quote - hashes
3530
- for (const [from, to] of [...keep, [close, close] as [number, number]])
3531
- if (from > cursor) {
3532
- blank(cursor, from)
3533
- cursor = to
3534
- } else cursor = Math.max(cursor, to)
3535
- return close
3536
- }
3537
- i++
3538
- }
3539
- blank(quote - hashes, chars.length)
3540
- return chars.length
3541
- }
3542
- // an interpolation's `)` ends the scan only when no paren is open inside
3543
- const scanCode = (i: number, nested: boolean): number => {
3544
- let parens = 0
3545
- while (i < chars.length) {
3546
- const char = source[i]!
3547
- if (char === '/' && source[i + 1] === '/') {
3548
- const end = source.indexOf('\n', i)
3549
- blank(i, end === -1 ? chars.length : end)
3550
- i = end === -1 ? chars.length : end
3551
- continue
3552
- }
3553
- if (char === '/' && source[i + 1] === '*') {
3554
- let j = i + 2
3555
- let depth = 1
3556
- while (j < chars.length && depth > 0) {
3557
- if (source.startsWith('/*', j)) {
3558
- depth++
3559
- j += 2
3560
- } else if (source.startsWith('*/', j)) {
3561
- depth--
3562
- j += 2
3563
- } else j++
3564
- }
3565
- blank(i, j)
3566
- i = j
3567
- continue
3568
- }
3569
- if (char === '#') {
3570
- const hashes = hashesAt(i)
3571
- const at = i + hashes
3572
- if (source[at] === '"') {
3573
- i = scanString(at, hashes)
3574
- continue
3575
- }
3576
- if (hashes > 0 && source[at] === '/') {
3577
- const mark = '#'.repeat(hashes)
3578
- let j = at + 1
3579
- while (
3580
- j < chars.length &&
3581
- !(source[j] === '/' && source.startsWith(mark, j + 1))
3582
- )
3583
- j++
3584
- blank(i, Math.min(chars.length, j + 1 + hashes))
3585
- i = Math.min(chars.length, j + 1 + hashes)
3586
- continue
3587
- }
3588
- i++
3589
- continue
3590
- }
3591
- if (char === '"') {
3592
- i = scanString(i, 0)
3593
- continue
3594
- }
3595
- if (char === '(') parens++
3596
- else if (char === ')') {
3597
- if (nested && parens === 0) return i
3598
- parens--
3599
- }
3600
- i++
3601
- }
3602
- return i
3603
- }
3604
- scanCode(0, false)
3605
- return chars.join('')
3606
- }
3607
-
3608
- // darwin declares these in Foundation; the guest networking module owns them.
3609
- const FOUNDATION_NETWORKING_TYPES = new Set([
3610
- 'NSURLConnection',
3611
- 'NSURLConnectionDataDelegate',
3612
- 'NSURLConnectionDelegate',
3613
- 'NSURLConnectionDownloadDelegate',
3614
- ])
3615
-
3616
- // Foundation overlay declarations live in the shared guest overlay module.
3617
- const FOUNDATION_OVERLAY_TYPES = new Set([
3618
- 'AsyncCharacterSequence',
3619
- 'AsyncLineSequence',
3620
- 'AsyncUnicodeScalarSequence',
3621
- 'BlockOperation',
3622
- 'DateComponentsFormatter',
3623
- 'ErrorUserInfoKey',
3624
- 'ListFormatter',
3625
- 'LocalizedStringResource',
3626
- 'MachError',
3627
- 'MeasurementFormatUnitUsage',
3628
- 'MessagePort',
3629
- 'NSAssertionHandler',
3630
- 'NSAttributedStringFormattingContextKey',
3631
- 'NSBundleResourceRequest',
3632
- 'NSConditionLock',
3633
- 'NSException',
3634
- 'NSExtensionItem',
3635
- 'NSFastEnumerationIterator',
3636
- 'NSFastEnumerationState',
3637
- 'NSFileAccessIntent',
3638
- 'NSFileManagerResumeSyncBehavior',
3639
- 'NSFileManagerSupportedSyncControls',
3640
- 'NSFileManagerUploadLocalVersionConflictPolicy',
3641
- 'NSFileProviderService',
3642
- 'NSFileProviderServiceName',
3643
- 'NSFileSecurity',
3644
- 'NSGrammaticalCase',
3645
- 'NSGrammaticalDefiniteness',
3646
- 'NSGrammaticalDetermination',
3647
- 'NSGrammaticalGender',
3648
- 'NSGrammaticalNumber',
3649
- 'NSGrammaticalPartOfSpeech',
3650
- 'NSGrammaticalPerson',
3651
- 'NSGrammaticalPronounType',
3652
- 'NSHashEnumerator',
3653
- 'NSHashTable',
3654
- 'NSHashTableCallBacks',
3655
- 'NSKeyValueOperator',
3656
- 'NSKeyValueSetMutationKind',
3657
- 'NSKeyValueSharedObservers',
3658
- // clang Foundation owns the linguistic tagger types. A Swift twin is ambiguous with the header.
3659
- 'NSMachPort',
3660
- 'NSMapEnumerator',
3661
- 'NSMapTable',
3662
- 'NSMapTableKeyCallBacks',
3663
- 'NSMapTableValueCallBacks',
3664
- 'NSMetadataItem',
3665
- 'NSMetadataQuery',
3666
- 'NSMetadataQueryAttributeValueTuple',
3667
- 'NSMetadataQueryDelegate',
3668
- 'NSMetadataQueryResultGroup',
3669
- 'NSPointerArray',
3670
- 'NSPredicateValidating',
3671
- 'NSProxy',
3672
- 'NSPurgeableData',
3673
- 'NSSecureUnarchiveFromDataTransformer',
3674
- 'NSUbiquitousKeyValueStore',
3675
- 'NSXPCCoder',
3676
- 'NSXPCConnection',
3677
- 'NSXPCInterface',
3678
- 'NSXPCListener',
3679
- 'NSXPCListenerDelegate',
3680
- 'NSXPCListenerEndpoint',
3681
- 'OperationQueue',
3682
- 'PredicateCodableConfiguration',
3683
- 'PresentationIntent',
3684
- 'SocketPort',
3685
- 'StringEncodingDetectionOptionsKey',
3686
- 'TermOfAddress',
3687
- 'URLFileProtection',
3688
- 'URLResource',
3689
- 'URLUbiquitousItemDownloadingStatus',
3690
- 'URLUbiquitousSharedItemPermissions',
3691
- 'URLUbiquitousSharedItemRole',
3692
- 'ValueTransformer',
3693
- ])
3694
-
3695
- // existing overlay globals retain their declaration and runtime owner.
3696
- const FOUNDATION_OVERLAY_GLOBALS = new Set([
3697
- 'CFBridgingRetain',
3698
- 'NSAllHashTableObjects',
3699
- 'NSAllMapTableKeys',
3700
- 'NSAllMapTableValues',
3701
- 'NSAllocateMemoryPages',
3702
- 'NSAssertionHandlerKey',
3703
- 'NSBuddhistCalendar',
3704
- 'NSBundleResourceRequestLoadingPriorityUrgent',
3705
- 'NSChineseCalendar',
3706
- 'NSCompareHashTables',
3707
- 'NSCompareMapTables',
3708
- 'NSCopyMemoryPages',
3709
- 'NSCountHashTable',
3710
- 'NSCountMapTable',
3711
- 'NSCreateHashTable',
3712
- 'NSCreateMapTable',
3713
- 'NSDeallocateMemoryPages',
3714
- 'NSEndHashTableEnumeration',
3715
- 'NSEndMapTableEnumeration',
3716
- 'NSEnumerateHashTable',
3717
- 'NSEnumerateMapTable',
3718
- 'NSExtensionItemAttachmentsKey',
3719
- 'NSExtensionItemAttributedContentTextKey',
3720
- 'NSExtensionItemAttributedTitleKey',
3721
- 'NSExtensionItemsAndErrorsKey',
3722
- 'NSExtensionJavaScriptFinalizeArgumentKey',
3723
- 'NSExtensionJavaScriptPreprocessingResultsKey',
3724
- 'NSFreeHashTable',
3725
- 'NSFreeMapTable',
3726
- 'NSGetUncaughtExceptionHandler',
3727
- 'NSGregorianCalendar',
3728
- 'NSHashGet',
3729
- 'NSHashInsert',
3730
- 'NSHashInsertIfAbsent',
3731
- 'NSHashInsertKnownAbsent',
3732
- 'NSHashRemove',
3733
- 'NSHebrewCalendar',
3734
- 'NSISO8601Calendar',
3735
- 'NSIndianCalendar',
3736
- 'NSIslamicCalendar',
3737
- 'NSIslamicCivilCalendar',
3738
- 'NSItemProviderPreferredImageSizeKey',
3739
- 'NSJapaneseCalendar',
3740
- 'NSLoadedClasses',
3741
- 'NSLocalizedFailureErrorKey',
3742
- 'NSLogPageSize',
3743
- 'NSMACHOperatingSystem',
3744
- 'NSMapGet',
3745
- 'NSMapInsert',
3746
- 'NSMapInsertIfAbsent',
3747
- 'NSMapInsertKnownAbsent',
3748
- 'NSMapMember',
3749
- 'NSMapRemove',
3750
- 'NSMultipleUnderlyingErrorsKey',
3751
- 'NSNextHashEnumeratorItem',
3752
- 'NSNextMapEnumeratorPair',
3753
- 'NSNonOwnedPointerHashCallBacks',
3754
- 'NSNonOwnedPointerMapKeyCallBacks',
3755
- 'NSNonOwnedPointerMapValueCallBacks',
3756
- 'NSNonOwnedPointerOrNullMapKeyCallBacks',
3757
- 'NSNonRetainedObjectHashCallBacks',
3758
- 'NSNonRetainedObjectMapKeyCallBacks',
3759
- 'NSNonRetainedObjectMapValueCallBacks',
3760
- 'NSObjectHashCallBacks',
3761
- 'NSObjectMapKeyCallBacks',
3762
- 'NSObjectMapValueCallBacks',
3763
- 'NSOpenStepRootDirectory',
3764
- 'NSOwnedObjectIdentityHashCallBacks',
3765
- 'NSOwnedPointerHashCallBacks',
3766
- 'NSOwnedPointerMapKeyCallBacks',
3767
- 'NSOwnedPointerMapValueCallBacks',
3768
- 'NSPersianCalendar',
3769
- 'NSPointerToStructHashCallBacks',
3770
- 'NSPropertyListErrorMaximum',
3771
- 'NSPropertyListErrorMinimum',
3772
- 'NSRepublicOfChinaCalendar',
3773
- 'NSResetHashTable',
3774
- 'NSResetMapTable',
3775
- 'NSSolarisOperatingSystem',
3776
- 'NSStringFromHashTable',
3777
- 'NSStringFromMapTable',
3778
- 'NSSunOSOperatingSystem',
3779
- 'NSTextCheckingAllCustomTypes',
3780
- 'NSTextCheckingAllSystemTypes',
3781
- 'NSTextCheckingAllTypes',
3782
- 'NSURLAuthenticationMethodHTMLForm',
3783
- 'NSURLAuthenticationMethodNTLM',
3784
- 'NSURLAuthenticationMethodNegotiate',
3785
- 'NSURLCredentialStorageRemoveSynchronizableCredentials',
3786
- 'NSURLErrorFileOutsideSafeArea',
3787
- 'NSURLProtectionSpaceFTP',
3788
- 'NSURLProtectionSpaceFTPProxy',
3789
- 'NSURLProtectionSpaceHTTP',
3790
- 'NSURLProtectionSpaceHTTPProxy',
3791
- 'NSURLProtectionSpaceHTTPS',
3792
- 'NSURLProtectionSpaceHTTPSProxy',
3793
- 'NSURLProtectionSpaceSOCKSProxy',
3794
- 'NSURLSessionUploadTaskResumeData',
3795
- 'NSUbiquitousFileErrorMaximum',
3796
- 'NSUbiquitousFileErrorMinimum',
3797
- 'NSUbiquitousKeyValueStoreAccountChange',
3798
- 'NSUbiquitousKeyValueStoreChangeReasonKey',
3799
- 'NSUbiquitousKeyValueStoreChangedKeysKey',
3800
- 'NSUbiquitousKeyValueStoreInitialSyncChange',
3801
- 'NSUbiquitousKeyValueStoreQuotaViolationChange',
3802
- 'NSUbiquitousKeyValueStoreServerChange',
3803
- 'NSUndoCloseGroupingRunLoopOrdering',
3804
- 'NSUndoManagerGroupIsDiscardableKey',
3805
- 'NSUserActivityErrorMaximum',
3806
- 'NSUserActivityErrorMinimum',
3807
- 'NSValidationErrorMaximum',
3808
- 'NSValidationErrorMinimum',
3809
- 'NSWindows95OperatingSystem',
3810
- 'NSWindowsNTOperatingSystem',
3811
- 'NSWrapCalendarComponents',
3812
- 'NSXPCConnectionCodeSigningRequirementFailure',
3813
- 'NSXPCConnectionErrorMaximum',
3814
- 'NSXPCConnectionErrorMinimum',
3815
- 'kCFStringEncodingASCII',
3816
- ])
3817
-
3818
- const CORE_FOUNDATION_OVERLAY_GLOBALS = new Set([
3819
- 'kCFCoreFoundationVersionNumber10_0',
3820
- 'kCFCoreFoundationVersionNumber10_0_3',
3821
- 'kCFCoreFoundationVersionNumber10_1',
3822
- 'kCFCoreFoundationVersionNumber10_10',
3823
- 'kCFCoreFoundationVersionNumber10_10_1',
3824
- 'kCFCoreFoundationVersionNumber10_10_2',
3825
- 'kCFCoreFoundationVersionNumber10_10_3',
3826
- 'kCFCoreFoundationVersionNumber10_10_4',
3827
- 'kCFCoreFoundationVersionNumber10_10_5',
3828
- 'kCFCoreFoundationVersionNumber10_10_Max',
3829
- 'kCFCoreFoundationVersionNumber10_11',
3830
- 'kCFCoreFoundationVersionNumber10_11_1',
3831
- 'kCFCoreFoundationVersionNumber10_11_2',
3832
- 'kCFCoreFoundationVersionNumber10_11_3',
3833
- 'kCFCoreFoundationVersionNumber10_11_4',
3834
- 'kCFCoreFoundationVersionNumber10_11_Max',
3835
- 'kCFCoreFoundationVersionNumber10_1_1',
3836
- 'kCFCoreFoundationVersionNumber10_1_2',
3837
- 'kCFCoreFoundationVersionNumber10_1_3',
3838
- 'kCFCoreFoundationVersionNumber10_1_4',
3839
- 'kCFCoreFoundationVersionNumber10_2',
3840
- 'kCFCoreFoundationVersionNumber10_2_1',
3841
- 'kCFCoreFoundationVersionNumber10_2_2',
3842
- 'kCFCoreFoundationVersionNumber10_2_3',
3843
- 'kCFCoreFoundationVersionNumber10_2_4',
3844
- 'kCFCoreFoundationVersionNumber10_2_5',
3845
- 'kCFCoreFoundationVersionNumber10_2_6',
3846
- 'kCFCoreFoundationVersionNumber10_2_7',
3847
- 'kCFCoreFoundationVersionNumber10_2_8',
3848
- 'kCFCoreFoundationVersionNumber10_3',
3849
- 'kCFCoreFoundationVersionNumber10_3_1',
3850
- 'kCFCoreFoundationVersionNumber10_3_2',
3851
- 'kCFCoreFoundationVersionNumber10_3_3',
3852
- 'kCFCoreFoundationVersionNumber10_3_4',
3853
- 'kCFCoreFoundationVersionNumber10_3_5',
3854
- 'kCFCoreFoundationVersionNumber10_3_6',
3855
- 'kCFCoreFoundationVersionNumber10_3_7',
3856
- 'kCFCoreFoundationVersionNumber10_3_8',
3857
- 'kCFCoreFoundationVersionNumber10_3_9',
3858
- 'kCFCoreFoundationVersionNumber10_4',
3859
- 'kCFCoreFoundationVersionNumber10_4_1',
3860
- 'kCFCoreFoundationVersionNumber10_4_10',
3861
- 'kCFCoreFoundationVersionNumber10_4_11',
3862
- 'kCFCoreFoundationVersionNumber10_4_2',
3863
- 'kCFCoreFoundationVersionNumber10_4_3',
3864
- 'kCFCoreFoundationVersionNumber10_4_4_Intel',
3865
- 'kCFCoreFoundationVersionNumber10_4_4_PowerPC',
3866
- 'kCFCoreFoundationVersionNumber10_4_5_Intel',
3867
- 'kCFCoreFoundationVersionNumber10_4_5_PowerPC',
3868
- 'kCFCoreFoundationVersionNumber10_4_6_Intel',
3869
- 'kCFCoreFoundationVersionNumber10_4_6_PowerPC',
3870
- 'kCFCoreFoundationVersionNumber10_4_7',
3871
- 'kCFCoreFoundationVersionNumber10_4_8',
3872
- 'kCFCoreFoundationVersionNumber10_4_9',
3873
- 'kCFCoreFoundationVersionNumber10_5',
3874
- 'kCFCoreFoundationVersionNumber10_5_1',
3875
- 'kCFCoreFoundationVersionNumber10_5_2',
3876
- 'kCFCoreFoundationVersionNumber10_5_3',
3877
- 'kCFCoreFoundationVersionNumber10_5_4',
3878
- 'kCFCoreFoundationVersionNumber10_5_5',
3879
- 'kCFCoreFoundationVersionNumber10_5_6',
3880
- 'kCFCoreFoundationVersionNumber10_5_7',
3881
- 'kCFCoreFoundationVersionNumber10_5_8',
3882
- 'kCFCoreFoundationVersionNumber10_6',
3883
- 'kCFCoreFoundationVersionNumber10_6_1',
3884
- 'kCFCoreFoundationVersionNumber10_6_2',
3885
- 'kCFCoreFoundationVersionNumber10_6_3',
3886
- 'kCFCoreFoundationVersionNumber10_6_4',
3887
- 'kCFCoreFoundationVersionNumber10_6_5',
3888
- 'kCFCoreFoundationVersionNumber10_6_6',
3889
- 'kCFCoreFoundationVersionNumber10_6_7',
3890
- 'kCFCoreFoundationVersionNumber10_6_8',
3891
- 'kCFCoreFoundationVersionNumber10_7',
3892
- 'kCFCoreFoundationVersionNumber10_7_1',
3893
- 'kCFCoreFoundationVersionNumber10_7_2',
3894
- 'kCFCoreFoundationVersionNumber10_7_3',
3895
- 'kCFCoreFoundationVersionNumber10_7_4',
3896
- 'kCFCoreFoundationVersionNumber10_7_5',
3897
- 'kCFCoreFoundationVersionNumber10_8',
3898
- 'kCFCoreFoundationVersionNumber10_8_1',
3899
- 'kCFCoreFoundationVersionNumber10_8_2',
3900
- 'kCFCoreFoundationVersionNumber10_8_3',
3901
- 'kCFCoreFoundationVersionNumber10_8_4',
3902
- 'kCFCoreFoundationVersionNumber10_9',
3903
- 'kCFCoreFoundationVersionNumber10_9_1',
3904
- 'kCFCoreFoundationVersionNumber10_9_2',
3905
- 'kCFCoreFoundationVersionNumber_iOS_4_0',
3906
- 'kCFCoreFoundationVersionNumber_iOS_4_1',
3907
- 'kCFCoreFoundationVersionNumber_iOS_4_2',
3908
- 'kCFCoreFoundationVersionNumber_iOS_4_3',
3909
- 'kCFCoreFoundationVersionNumber_iOS_5_0',
3910
- 'kCFCoreFoundationVersionNumber_iOS_5_1',
3911
- 'kCFCoreFoundationVersionNumber_iOS_6_0',
3912
- 'kCFCoreFoundationVersionNumber_iOS_6_1',
3913
- 'kCFCoreFoundationVersionNumber_iOS_7_0',
3914
- 'kCFCoreFoundationVersionNumber_iOS_7_1',
3915
- 'kCFCoreFoundationVersionNumber_iOS_8_0',
3916
- 'kCFCoreFoundationVersionNumber_iOS_8_1',
3917
- 'kCFCoreFoundationVersionNumber_iOS_8_2',
3918
- 'kCFCoreFoundationVersionNumber_iOS_8_3',
3919
- 'kCFCoreFoundationVersionNumber_iOS_8_4',
3920
- 'kCFCoreFoundationVersionNumber_iOS_8_x_Max',
3921
- 'kCFCoreFoundationVersionNumber_iOS_9_0',
3922
- 'kCFCoreFoundationVersionNumber_iOS_9_1',
3923
- 'kCFCoreFoundationVersionNumber_iOS_9_2',
3924
- 'kCFCoreFoundationVersionNumber_iOS_9_3',
3925
- 'kCFCoreFoundationVersionNumber_iOS_9_4',
3926
- 'kCFCoreFoundationVersionNumber_iOS_9_x_Max',
3927
- 'kCFCoreFoundationVersionNumber_iPhoneOS_2_0',
3928
- 'kCFCoreFoundationVersionNumber_iPhoneOS_2_1',
3929
- 'kCFCoreFoundationVersionNumber_iPhoneOS_2_2',
3930
- 'kCFCoreFoundationVersionNumber_iPhoneOS_3_0',
3931
- 'kCFCoreFoundationVersionNumber_iPhoneOS_3_1',
3932
- 'kCFCoreFoundationVersionNumber_iPhoneOS_3_2',
3933
- ])
3934
-
3935
2552
  // the Darwin CoreFoundation overlay exposes Foundation's geometry identities.
3936
2553
  const CORE_FOUNDATION_GEOMETRY_TYPES = new Set([
3937
2554
  'CGFloat',
@@ -3972,21 +2589,6 @@ const CORE_FOUNDATION_HANDLE_IMPORTS = [
3972
2589
  ])
3973
2590
  .join('; ')
3974
2591
 
3975
- // the guest module that owns a name darwin's Foundation declares
3976
- export function foundationOwnerOf(name: string): string | undefined {
3977
- if (name === 'NSKeyValueObservedChange' || name === 'NSKeyValueObservation')
3978
- return 'PeachObjC'
3979
- if (name === 'DispatchData') return 'Dispatch'
3980
- if (FOUNDATION_NETWORKING_TYPES.has(name)) return 'FoundationNetworking'
3981
- if (
3982
- FOUNDATION_OVERLAY_TYPES.has(name) ||
3983
- FOUNDATION_OVERLAY_GLOBALS.has(name) ||
3984
- CORE_FOUNDATION_OVERLAY_GLOBALS.has(name)
3985
- )
3986
- return 'PeachFoundation'
3987
- return undefined
3988
- }
3989
-
3990
2592
  // dependency sources take the same platform branches as app sources
3991
2593
  function swiftPackageSourceAsIOS(source: string): string {
3992
2594
  return swiftConditionsAsIOS(source, swiftCodeScan(source).lineStarts)
@@ -4364,239 +2966,6 @@ export function neutralizedNativeMain(source: string): string {
4364
2966
  return `${out}\n#ifdef __cplusplus\nextern "C"\n#endif\n__attribute__((swiftcall)) int __peach_call_native_main(int argc, char **argv) { ${unused}return __peach_native_main(${args}); }\n`
4365
2967
  }
4366
2968
 
4367
- // a c-family entry: a main definition outside comments and strings. headers
4368
- // never compile, so only sources are scanned.
4369
- /** the macro environment a c-family entry guard evaluates against. */
4370
- export interface SwiftCMacroEnvironment {
4371
- /** the target's -D set, with values where given. */
4372
- defines: ReadonlyMap<string, string | undefined>
4373
- /** the compiler's own predefines for the unit's language. */
4374
- predefines: ReadonlyMap<string, string | undefined>
4375
- /** names any of the target's own sources or headers defines. */
4376
- targetDefined: ReadonlySet<string>
4377
- }
4378
-
4379
- const emptyMacroEnvironment: SwiftCMacroEnvironment = {
4380
- defines: new Map(),
4381
- predefines: new Map(),
4382
- targetDefined: new Set(),
4383
- }
4384
-
4385
- // whether the environment defines the name: -D and predefines decide,
4386
- // a name only the target's own sources define is undecided (order and
4387
- // conditions are not evaluated), and a name nowhere visible is absent.
4388
- function cMacroDefined(name: string, env: SwiftCMacroEnvironment): boolean | undefined {
4389
- if (env.defines.has(name) || env.predefines.has(name)) return true
4390
- if (env.targetDefined.has(name)) return undefined
4391
- return false
4392
- }
4393
-
4394
- function cMacroIntOrTrue(value: string | undefined): boolean | undefined {
4395
- if (value === undefined) return true
4396
- if (/^0[xX][0-9a-fA-F]+[uUlL]*$/.test(value) || /^\d+[uUlL]*$/.test(value))
4397
- return Number.parseInt(value) !== 0
4398
- return undefined
4399
- }
4400
-
4401
- function cMacroBareValue(name: string, env: SwiftCMacroEnvironment): boolean | undefined {
4402
- if (env.defines.has(name)) return cMacroIntOrTrue(env.defines.get(name))
4403
- if (env.predefines.has(name)) return cMacroIntOrTrue(env.predefines.get(name))
4404
- if (env.targetDefined.has(name)) return undefined
4405
- return false
4406
- }
4407
-
4408
- function cMacroNegated(name: string, env: SwiftCMacroEnvironment): boolean | undefined {
4409
- return kleeneNot(cMacroDefined(name, env))
4410
- }
4411
-
4412
- // a preprocessor condition the macro environment decides, or undefined when
4413
- // the text needs the real preprocessor (comparisons, function-like macros,
4414
- // __has_include and the like). only defined-ness, boolean operators and
4415
- // integer literals evaluate; the rest is undecided.
4416
- function cConditionValue(
4417
- expression: string,
4418
- env: SwiftCMacroEnvironment,
4419
- ): boolean | undefined {
4420
- let i = 0
4421
- const skipSpaces = () => {
4422
- while (i < expression.length && /\s/.test(expression[i]!)) i++
4423
- }
4424
- const parseOr = (): boolean | undefined => {
4425
- let value = parseAnd()
4426
- for (;;) {
4427
- skipSpaces()
4428
- if (!expression.startsWith('||', i)) return value
4429
- i += 2
4430
- value = kleeneOr(value, parseAnd())
4431
- }
4432
- }
4433
- const parseAnd = (): boolean | undefined => {
4434
- let value = parseUnary()
4435
- for (;;) {
4436
- skipSpaces()
4437
- if (!expression.startsWith('&&', i)) return value
4438
- i += 2
4439
- value = kleeneAnd(value, parseUnary())
4440
- }
4441
- }
4442
- const parseUnary = (): boolean | undefined => {
4443
- skipSpaces()
4444
- if (expression[i] === '!') {
4445
- i++
4446
- return kleeneNot(parseUnary())
4447
- }
4448
- if (expression[i] === '(') {
4449
- i++
4450
- const value = parseOr()
4451
- skipSpaces()
4452
- return expression[i] === ')' ? (i++, value) : undefined
4453
- }
4454
- const defined = /^defined\b/.exec(expression.slice(i))
4455
- if (defined) {
4456
- i += defined[0].length
4457
- skipSpaces()
4458
- const parenthesized = expression[i] === '('
4459
- if (parenthesized) {
4460
- i++
4461
- skipSpaces()
4462
- }
4463
- const name = /^\w+/.exec(expression.slice(i))?.[0]
4464
- if (!name) return undefined
4465
- i += name.length
4466
- skipSpaces()
4467
- if (parenthesized) {
4468
- if (expression[i] !== ')') return undefined
4469
- i++
4470
- }
4471
- return cMacroDefined(name, env)
4472
- }
4473
- const literal = /^(0[xX][0-9a-fA-F]+|\d+)[uUlL]*/.exec(expression.slice(i))
4474
- if (literal) {
4475
- i += literal[0].length
4476
- return Number(literal[1]) !== 0
4477
- }
4478
- const name = /^\w+/.exec(expression.slice(i))?.[0]
4479
- if (!name) return undefined
4480
- i += name.length
4481
- return cMacroBareValue(name, env)
4482
- }
4483
- const value = parseOr()
4484
- skipSpaces()
4485
- return i === expression.length ? value : undefined
4486
- }
4487
-
4488
- // the lines xcode's preprocessor keeps: conditional directives evaluated
4489
- // against the macro environment, with undecided branches kept, so an entry
4490
- // guard the text cannot decide still counts.
4491
- function cActiveCode(code: string, env: SwiftCMacroEnvironment): string {
4492
- const kept: string[] = []
4493
- const stack: { parent: boolean; taken: boolean }[] = []
4494
- let active = true
4495
- for (const line of code.replace(/\\\r?\n/g, '').split('\n')) {
4496
- const directive =
4497
- /^\s*#\s*(if|ifdef|ifndef|elif|elifdef|elifndef|else|endif)\b(.*)$/.exec(line)
4498
- if (!directive) {
4499
- if (active) kept.push(line)
4500
- continue
4501
- }
4502
- const keyword = directive[1]!
4503
- const rest = directive[2]!.trim()
4504
- if (keyword === 'if' || keyword === 'ifdef' || keyword === 'ifndef') {
4505
- const name = /^\w+$/.exec(rest)?.[0]
4506
- const value =
4507
- keyword === 'if'
4508
- ? cConditionValue(rest, env)
4509
- : name === undefined
4510
- ? undefined
4511
- : keyword === 'ifdef'
4512
- ? cMacroDefined(name, env)
4513
- : cMacroNegated(name, env)
4514
- stack.push({ parent: active, taken: value === true })
4515
- active = active && value !== false
4516
- } else if (keyword === 'endif') {
4517
- active = stack.pop()?.parent ?? true
4518
- } else if (stack.length === 0) {
4519
- continue
4520
- } else {
4521
- const frame = stack[stack.length - 1]!
4522
- if (keyword === 'else') {
4523
- active = frame.parent && !frame.taken
4524
- frame.taken = true
4525
- } else {
4526
- const name = /^\w+$/.exec(rest)?.[0]
4527
- const value =
4528
- keyword === 'elif'
4529
- ? cConditionValue(rest, env)
4530
- : name === undefined
4531
- ? undefined
4532
- : keyword === 'elifdef'
4533
- ? cMacroDefined(name, env)
4534
- : cMacroNegated(name, env)
4535
- const branch = !frame.taken && value !== false
4536
- if (branch && value === true) frame.taken = true
4537
- active = frame.parent && branch
4538
- }
4539
- }
4540
- }
4541
- return kept.join('\n')
4542
- }
4543
-
4544
- // the source with comments and string and character literals removed,
4545
- // newlines kept so directive lines stay intact.
4546
- function stripCCode(source: string): string {
4547
- let code = ''
4548
- let i = 0
4549
- while (i < source.length) {
4550
- if (source.startsWith('//', i)) {
4551
- const end = source.indexOf('\n', i)
4552
- i = end === -1 ? source.length : end
4553
- } else if (source.startsWith('/*', i)) {
4554
- const end = source.indexOf('*/', i + 2)
4555
- i = end === -1 ? source.length : end + 2
4556
- } else if (source[i] === '"' || source[i] === "'") {
4557
- const quote = source[i]!
4558
- i++
4559
- while (i < source.length && source[i] !== quote) i += source[i] === '\\' ? 2 : 1
4560
- i++
4561
- } else {
4562
- code += source[i]
4563
- i++
4564
- }
4565
- }
4566
- return code
4567
- }
4568
-
4569
- // whether the unit's wasm code takes its own return address, which
4570
- // the WebAssembly backend rejects ("hasn't implemented __builtin_return_address"):
4571
- // native machine code the target has no lowering for, like assembly. branches
4572
- // the native architecture macros guard are not wasm code.
4573
- const wasmMacroEnvironment: SwiftCMacroEnvironment = {
4574
- ...emptyMacroEnvironment,
4575
- defines: new Map([
4576
- ['__wasm__', '1'],
4577
- ['__wasm64__', '1'],
4578
- ['__wasi__', '1'],
4579
- ]),
4580
- }
4581
- export function swiftCTakesReturnAddress(source: string): boolean {
4582
- if (!source.includes('__builtin_return_address')) return false
4583
- return /\b__builtin_return_address\s*\(/.test(
4584
- cActiveCode(stripCCode(source), wasmMacroEnvironment),
4585
- )
4586
- }
4587
-
4588
- // every name the given sources define. order and conditions are not
4589
- // evaluated: a name defined anywhere makes its guards undecided.
4590
- export function swiftCDefinedNames(sources: Iterable<string>): Set<string> {
4591
- const names = new Set<string>()
4592
- for (const source of sources)
4593
- for (const line of stripCCode(source).split('\n')) {
4594
- const name = /^\s*#\s*define\s+([A-Za-z_]\w*)/.exec(line)?.[1]
4595
- if (name) names.add(name)
4596
- }
4597
- return names
4598
- }
4599
-
4600
2969
  type SwiftCPredefinesTable = {
4601
2970
  release: string
4602
2971
  languages: Record<string, Record<string, string | null>>