peachsim 0.1.2608 → 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 (151) hide show
  1. package/cli/commands/perf-native.ts +120 -6
  2. package/cli/drivers/playwright-provisioning.ts +4 -1
  3. package/dist-lib/agent-daemon-client.cjs +1 -1
  4. package/dist-lib/agent-events.cjs +1 -1
  5. package/dist-lib/attached-projects.cjs +1 -1
  6. package/dist-lib/auth/shared-session.cjs +1 -1
  7. package/dist-lib/backend-origin.cjs +1 -1
  8. package/dist-lib/beta.cjs +1 -1
  9. package/dist-lib/beta.mjs +2 -2
  10. package/dist-lib/bridge-constants.cjs +1 -1
  11. package/dist-lib/bridge-contract-input.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.mjs +5 -5
  13. package/dist-lib/bridge-contract.cjs +1 -1
  14. package/dist-lib/bridge-contract.mjs +3 -3
  15. package/dist-lib/bundle-channel.cjs +60485 -60177
  16. package/dist-lib/capture-contract.cjs +1 -1
  17. package/dist-lib/capture-contract.mjs +3 -3
  18. package/dist-lib/cloud-contract.cjs +1 -1
  19. package/dist-lib/cloud-contract.mjs +3 -3
  20. package/dist-lib/cloud-test-args.cjs +1 -1
  21. package/dist-lib/cloud-test-args.mjs +2 -2
  22. package/dist-lib/cloud.cjs +1 -1
  23. package/dist-lib/cloud.mjs +7 -7
  24. package/dist-lib/config.cjs +1 -1
  25. package/dist-lib/config.mjs +5 -5
  26. package/dist-lib/detox/index.cjs +1 -1
  27. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  28. package/dist-lib/esm-chunks/{acorn-4QDEL7IO.mjs → acorn-L2SFCOHG.mjs} +3 -3
  29. package/dist-lib/esm-chunks/{chunk-4C57RZXG.mjs → chunk-2LJTZ2KG.mjs} +17 -328
  30. package/dist-lib/esm-chunks/{chunk-X6CONUT6.mjs → chunk-42NDD4R7.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-F724FZHJ.mjs → chunk-73NIGS7D.mjs} +1490 -3950
  32. package/dist-lib/esm-chunks/{chunk-KNCWQQZG.mjs → chunk-CUBTZPSZ.mjs} +1 -1
  33. package/dist-lib/esm-chunks/chunk-EU5WMP5O.mjs +322 -0
  34. package/dist-lib/esm-chunks/{chunk-NXG27NGU.mjs → chunk-EYSNLE5V.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-IKFFQXJN.mjs → chunk-FP447MCW.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-JIW4PICV.mjs → chunk-HMTSU22Q.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-7KU5ROOE.mjs → chunk-KTAGV5U6.mjs} +14 -12
  38. package/dist-lib/esm-chunks/{chunk-3DUFAH5J.mjs → chunk-MJP4WOSX.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-H3QASOKR.mjs → chunk-MK4DOEDN.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-ZFI5OF6U.mjs → chunk-N3M5KT33.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-F2FHFORX.mjs → chunk-N7XU2WWO.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-UHYHEJ3N.mjs → chunk-RN73P2DY.mjs} +34 -28
  43. package/dist-lib/esm-chunks/{chunk-VICI67J5.mjs → chunk-VDLPNJ6P.mjs} +1 -1
  44. package/dist-lib/esm-chunks/chunk-W3LNUIUA.mjs +2655 -0
  45. package/dist-lib/esm-chunks/{chunk-R25MOOFS.mjs → chunk-WBQFHIGS.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-YBMBAXAZ.mjs → chunk-WZHEW7Z7.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-RTXAZMTP.mjs → chunk-X74N3K5N.mjs} +4 -4
  48. package/dist-lib/esm-chunks/{chunk-IJX7PBNG.mjs → chunk-XN74REO2.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{chunk-RZLGVWHK.mjs → chunk-YLUD2UET.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-BEWJL2LY.mjs → chunk-YVLXYLNV.mjs} +1 -1
  51. package/dist-lib/esm-chunks/{chunk-W5EHCHDD.mjs → chunk-YYGSN3BN.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{chunk-GPPOU5DO.mjs → chunk-ZZB2LFYV.mjs} +1 -1
  53. package/dist-lib/esm-chunks/{metro-layout-parser-YWPJI3L6.mjs → metro-layout-parser-VDPXJ7LW.mjs} +3 -3
  54. package/dist-lib/esm-chunks/{swift-package-prebuilt-MWTLCMQD.mjs → swift-package-prebuilt-HRPDLN2P.mjs} +14 -11
  55. package/dist-lib/esm-chunks/{swift-sdk-app-module-PF5QMK5X.mjs → swift-sdk-app-module-5DOGMU3M.mjs} +16 -14
  56. package/dist-lib/esm-chunks/{swift-sdk-image-5IMAACRF.mjs → swift-sdk-image-W3UU4H4L.mjs} +16 -14
  57. package/dist-lib/esm-chunks/{swift-sdk-image-producer-JPIJI25U.mjs → swift-sdk-image-producer-OJWD6ZOH.mjs} +8 -6
  58. package/dist-lib/expo-swift-bundle.cjs +42524 -42216
  59. package/dist-lib/expo-swift-metadata.cjs +1 -1
  60. package/dist-lib/expo-swift-metadata.mjs +7 -7
  61. package/dist-lib/home-paths.cjs +1 -1
  62. package/dist-lib/host/bridge-host.cjs +43716 -43244
  63. package/dist-lib/host/fetch-proxy-handler.cjs +670 -645
  64. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  65. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  66. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  67. package/dist-lib/host/websocket-proxy.cjs +1 -1
  68. package/dist-lib/index.cjs +1 -1
  69. package/dist-lib/kotlin-host.cjs +1 -1
  70. package/dist-lib/menu.cjs +1 -1
  71. package/dist-lib/menu.mjs +3 -3
  72. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  73. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  74. package/dist-lib/metro-production-bundle.cjs +1 -1
  75. package/dist-lib/metro-production-bundle.mjs +4 -4
  76. package/dist-lib/native-app-identity-project.cjs +1499 -2889
  77. package/dist-lib/native-app-identity-project.mjs +317 -339
  78. package/dist-lib/native-app-identity.cjs +1 -1
  79. package/dist-lib/native-app-identity.mjs +6 -6
  80. package/dist-lib/native-firebase-metadata.cjs +1 -1
  81. package/dist-lib/native-firebase-metadata.mjs +3 -3
  82. package/dist-lib/pdfium-raster.cjs +1 -1
  83. package/dist-lib/pdfium-raster.mjs +2 -2
  84. package/dist-lib/plist.cjs +1 -1
  85. package/dist-lib/plist.mjs +3 -3
  86. package/dist-lib/profiles.cjs +1 -1
  87. package/dist-lib/public-brand.cjs +1 -1
  88. package/dist-lib/public-origins-lib-esm.json +166 -154
  89. package/dist-lib/public-origins-lib.json +141 -198
  90. package/dist-lib/react-native-host-modules.cjs +1 -1
  91. package/dist-lib/react-native-host-modules.mjs +2 -2
  92. package/dist-lib/reap-browser.cjs +1 -1
  93. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  94. package/dist-lib/sdk.cjs +1 -1
  95. package/dist-lib/sdk.mjs +8 -8
  96. package/dist-lib/skills.cjs +38979 -38507
  97. package/dist-lib/swift-compile.cjs +12239 -12121
  98. package/dist-lib/swift-compile.mjs +36 -33
  99. package/dist-lib/swift-package.cjs +1 -1
  100. package/dist-lib/swift-package.mjs +3 -3
  101. package/dist-lib/swift-submit.cjs +1 -1
  102. package/dist-lib/swift-submit.mjs +6 -6
  103. package/dist-lib/swift-svg-raster.cjs +1 -1
  104. package/dist-lib/swift-svg-raster.mjs +2 -2
  105. package/dist-lib/swift-toolchain.cjs +1 -1
  106. package/dist-lib/swift.cjs +1 -1
  107. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  108. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  109. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  110. package/dist-lib/vendor/acorn.cjs +1 -1
  111. package/dist-lib/vendor/magic-string.cjs +1 -1
  112. package/dist-lib/vendor/stream-json.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase.cjs +1 -1
  118. package/dist-lib/vendor/terser.cjs +1 -1
  119. package/dist-lib/vendor/valibot.cjs +1 -1
  120. package/dist-lib/vendor/ws.cjs +1 -1
  121. package/dist-lib/vendor/zod.cjs +1 -1
  122. package/dist-lib/worklet-executable.cjs +1 -1
  123. package/dist-lib/worklet-executable.mjs +3 -3
  124. package/dist-types/packages/peach-engine/src/ios/apps/canvas-map-data.d.ts +13 -0
  125. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +3 -0
  126. package/package.json +1 -1
  127. package/src/agent-prompt.ts +15 -2
  128. package/src/binaryen.lock.json +3 -3
  129. package/src/genrule-archives.ts +5 -2
  130. package/src/native-framework-compiler.ts +1 -1
  131. package/src/native-static-libraries.ts +2 -3
  132. package/src/native-swift-slices.ts +1 -1
  133. package/src/nitro-dependencies.ts +3 -7
  134. package/src/one-native-controls-package.ts +165 -11
  135. package/src/oneNativeControlsContract.ts +1 -0
  136. package/src/rive-runtime-dependencies.ts +1 -2
  137. package/src/swift-compile.ts +165 -1796
  138. package/src/swift-compiler-digest.ts +2 -0
  139. package/src/swift-distribution.ts +39 -15
  140. package/src/swift-objc-compile.ts +194 -32
  141. package/src/swift-package-manifest.ts +6 -29
  142. package/src/swift-packages.ts +6 -14
  143. package/src/swift-sdk-surface.ts +1811 -0
  144. package/src/swift-standin-digest.ts +28 -5
  145. package/src/swift-standins.ts +16 -19
  146. package/src/swift-wasm-archive.ts +200 -0
  147. package/src/swift-wasm-prune.ts +3 -93
  148. package/src/swift-wasm64-native-source.ts +4 -2
  149. package/src/swiftWasm64ConfigContract.ts +10 -0
  150. package/src/wasm-optimize.ts +18 -14
  151. package/src/xcode-project.ts +2 -4
@@ -0,0 +1,1811 @@
1
+ import { execFileSync, spawnSync } from 'node:child_process'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import {
4
+ chmodSync,
5
+ copyFileSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ mkdtempSync,
9
+ readFileSync,
10
+ readdirSync,
11
+ realpathSync,
12
+ renameSync,
13
+ rmSync,
14
+ statSync,
15
+ utimesSync,
16
+ writeFileSync,
17
+ } from 'node:fs'
18
+ import os from 'node:os'
19
+ import path from 'node:path'
20
+ import { windowAdmission } from './admitted-mac-build'
21
+ import { cacheDir } from './home-paths'
22
+ import {
23
+ parseSwiftDistributionManifest,
24
+ SWIFT_DISTRIBUTION_MANIFEST,
25
+ SWIFT_DISTRIBUTION_OBJC_SELECTORS,
26
+ type SwiftDistributionManifest,
27
+ } from './swift-distribution-contract'
28
+ import { swiftManifestDeclarations } from './swift-package'
29
+ import {
30
+ swiftSharedSdkInputFiles,
31
+ swiftSharedSdkSourceRoot,
32
+ swiftSharedSdkViewOptions,
33
+ } from './swift-shared-sdk'
34
+ import {
35
+ refreshSwiftCacheHold,
36
+ swiftCacheDir,
37
+ swiftCompiler,
38
+ swiftEnvironment,
39
+ swiftSourceSdk,
40
+ swiftToolchain,
41
+ type SwiftWasmSdk,
42
+ } from './swift-toolchain'
43
+ import { isSwiftResourcePath } from './swiftContract'
44
+ import { SWIFT_WASM_TRIPLE } from './swiftTargetContract'
45
+
46
+ export function swiftBuildJobs(): number {
47
+ const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES)
48
+ const parallelism = Math.max(1, os.availableParallelism())
49
+ if (!Number.isInteger(admittedCores) || admittedCores <= 0)
50
+ return Math.min(4, Math.max(1, Math.floor(parallelism / 2)))
51
+ const cores = Math.min(admittedCores, parallelism)
52
+ if (process.platform === 'darwin') return cores
53
+ const memory =
54
+ process.env.TM_EXEC_ADMITTED === '1' && process.env.LINUX_BUILD_SCOPE
55
+ ? Number(process.env.TM_EXEC_LINUX_MEMORY_MAX)
56
+ : NaN
57
+ const memoryJobs =
58
+ Number.isSafeInteger(memory) && memory > 0
59
+ ? Math.max(1, Math.floor(memory / (2 * 1024 ** 3)))
60
+ : 8
61
+ return Math.min(cores, memoryJobs)
62
+ }
63
+
64
+ /**
65
+ * the prebuilt distribution at a module root, or null for a sootsim-swift
66
+ * source checkout. an installed peach links the distribution: compiled
67
+ * modules, one static library and host macro plugins, and no source
68
+ * (docs/peach/swift/distribution.md).
69
+ */
70
+ export function swiftDistributionAt(root: string): SwiftDistributionManifest | null {
71
+ const file = path.join(root, SWIFT_DISTRIBUTION_MANIFEST)
72
+ const stat = statSync(file, { bigint: true, throwIfNoEntry: false })
73
+ if (!stat) return null
74
+ // a large app asks once per target; the megabytes of manifest parse once
75
+ // per published file.
76
+ const identity = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}`
77
+ const cached = distributionManifests.get(file)
78
+ if (cached?.identity === identity) return cached.manifest
79
+ const manifest = parseSwiftDistributionManifest(JSON.parse(readFileSync(file, 'utf8')))
80
+ distributionManifests.set(file, { identity, manifest })
81
+ return manifest
82
+ }
83
+ const distributionManifests = new Map<
84
+ string,
85
+ { identity: string; manifest: SwiftDistributionManifest }
86
+ >()
87
+
88
+ // the selector map and host macro plugins every app compile names, at a path
89
+ // named by their bytes: a change to either changes every compile command.
90
+ const distributionCompileViews = new WeakMap<SwiftDistributionManifest, string>()
91
+ export function swiftDistributionCompileView(
92
+ moduleRoot: string,
93
+ distribution: SwiftDistributionManifest,
94
+ ): string {
95
+ let view = distributionCompileViews.get(distribution)
96
+ if (!view || !existsSync(view)) {
97
+ const inputs = Object.entries(distribution.files)
98
+ .filter(
99
+ ([file]) =>
100
+ file.startsWith('host/') || file === SWIFT_DISTRIBUTION_OBJC_SELECTORS,
101
+ )
102
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
103
+ const digest = createHash('sha256').update(JSON.stringify(inputs)).digest('hex')
104
+ view = path.join(swiftCacheDir(), 'swift-sdk-views', `compile-${digest}`)
105
+ if (!existsSync(view)) {
106
+ mkdirSync(path.dirname(view), { recursive: true })
107
+ const staging = mkdtempSync(`${view}-`)
108
+ try {
109
+ chmodSync(staging, 0o755)
110
+ for (const [file] of inputs) {
111
+ if (!isSwiftResourcePath(file))
112
+ throw new Error(`invalid Swift distribution compile path ${file}`)
113
+ const destination = path.join(staging, file)
114
+ mkdirSync(path.dirname(destination), { recursive: true })
115
+ copyFileSync(path.join(moduleRoot, file), destination)
116
+ }
117
+ try {
118
+ renameSync(staging, view)
119
+ } catch (error) {
120
+ if (!existsSync(view)) throw error
121
+ }
122
+ } finally {
123
+ rmSync(staging, { recursive: true, force: true })
124
+ }
125
+ }
126
+ distributionCompileViews.set(distribution, view)
127
+ }
128
+ const now = new Date()
129
+ utimesSync(view, now, now)
130
+ refreshSwiftCacheHold(view)
131
+ return view
132
+ }
133
+
134
+ /**
135
+ * frameworks without Swift declarations that stage by the headers consumers
136
+ * import: React's umbrella imports UIKit headers (UIKeyCommand, UIFontMetrics,
137
+ * UIAccessibilityElement) the sdk's clang UIKit surface does not carry. an
138
+ * app's React headers never take Peach's React interface, whose generated
139
+ * header imports a React/React.h the prebuilt framework lacks.
140
+ */
141
+ export const REACH_STAGED_FRAMEWORKS: ReadonlySet<string> = new Set(['React'])
142
+
143
+ /**
144
+ * the Objective-C interface an SDK module defines: the names Swift owns and
145
+ * its generated header. a distribution ships the header; a source checkout
146
+ * names them by `@objc(Name)` and reads the header its module build emitted
147
+ * (`.build/host`). a module with no emitted header has no interface in either,
148
+ * so its original Objective-C headers keep their declarations.
149
+ */
150
+ export function swiftModuleInterface(
151
+ moduleRoot: string,
152
+ name: string,
153
+ ): { declared: ReadonlySet<string>; header: string } | null {
154
+ if (REACH_STAGED_FRAMEWORKS.has(name)) return null
155
+ if (swiftDistributionAt(moduleRoot)) {
156
+ const file = path.join(moduleRoot, 'modules', `${name}-Swift.h`)
157
+ if (!existsSync(file)) return null
158
+ const header = clangInterfaceHeader(readFileSync(file, 'utf8'), moduleRoot)
159
+ return { declared: swiftInterfaceDeclarations(header), header }
160
+ }
161
+ const sources = path.join(moduleRoot, 'Sources', name)
162
+ const built = path.join(moduleRoot, '.build/host', `${name}-Swift.h`)
163
+ if (!existsSync(sources) || !existsSync(built)) return null
164
+ const declared = new Set<string>()
165
+ for (const file of readdirSync(sources, { recursive: true, encoding: 'utf8' }))
166
+ if (file.endsWith('.swift'))
167
+ // an NSObject subclass is an Objective-C class named as it is in Swift
168
+ for (const [, objc, subclass] of readFileSync(
169
+ path.join(sources, file),
170
+ 'utf8',
171
+ ).matchAll(
172
+ /@objc\((\w+)\)\s+(?:\w+\s+)*?(?:protocol|class)\s|^(?:public|open)\s+(?:final\s+)?class\s+(\w+)\s*:\s*NSObject\b/gm,
173
+ ))
174
+ declared.add((objc ?? subclass)!)
175
+ if (declared.size === 0) return null
176
+ return {
177
+ declared,
178
+ header: clangInterfaceHeader(readFileSync(built, 'utf8'), moduleRoot),
179
+ }
180
+ }
181
+
182
+ // the compiler imports the module that defines a type, and UIKit's declarations
183
+ // live in UIKitCore/UIKitText, which only the umbrella UIKit module represents
184
+ // to clang. CoreFoundation's CGFloat lives in the Swift CoreFoundation overlay,
185
+ // while clang's Foundation umbrella owns public Core Foundation types,
186
+ // networking classes and the classes PeachFoundation implements. a framework's
187
+ // enums and constants clang target repeats declarations its headers own.
188
+ export function clangInterfaceHeader(header: string, moduleRoot: string): string {
189
+ const distribution = swiftDistributionAt(moduleRoot) !== null
190
+ const frameworks = path.join(
191
+ swiftSharedSdkSourceRoot(moduleRoot, distribution),
192
+ 'System/Library/Frameworks',
193
+ )
194
+ let references: Set<string> | undefined
195
+ const imported = new Set(
196
+ [...header.matchAll(/^@import (\w+);$/gm)].map((match) => match[1]!),
197
+ )
198
+ return header
199
+ .replace(/^@import (?:UIKitCore|UIKitText);$/gm, '@import UIKit;')
200
+ .replace(
201
+ /^@import ((\w+?)(?:Enums|Constants));$/gm,
202
+ (_, module: string, framework: string) => {
203
+ const imports = [`@import ${framework};`]
204
+ imported.add(framework)
205
+ const directory = distribution
206
+ ? path.join(moduleRoot, 'modules', module)
207
+ : path.join(moduleRoot, 'Sources', module, 'include')
208
+ if (!existsSync(directory)) return imports[0]!
209
+
210
+ if (!references) {
211
+ references = new Set(header.match(/\b[A-Z]\w*\b/g))
212
+ for (const name of objcEnumerations(header)) references.delete(name)
213
+ }
214
+ const owners = sdkObjCDeclarationOwners(frameworks)
215
+ for (const name of clangDeclarationEnums(directory)) {
216
+ const owner = references.has(name) ? owners.get(name) : undefined
217
+ if (!owner || imported.has(owner)) continue
218
+ imported.add(owner)
219
+ imports.push(`@import ${owner};`)
220
+ }
221
+ return imports.join('\n')
222
+ },
223
+ )
224
+ .replace(
225
+ /^@import (?:CoreFoundation(?:_Private)?|FoundationNetworking|PeachFoundation);$/gm,
226
+ '@import Foundation;',
227
+ )
228
+ .replace(/\b_TtC10Foundation\d+(NS\w+)\b/g, '$1')
229
+ .replace(/\b__attribute__\(\(objc_subclassing_restricted\)\)\s*/g, '')
230
+ }
231
+
232
+ export const objcEnumerations = (header: string): string[] =>
233
+ [
234
+ ...header.matchAll(
235
+ /^\s*typedef\s+(?:NS|CF|SWIFT)_\w*(?:ENUM|OPTIONS)\w*\s*\(\s*\w+\s*,\s*(\w+)\b/gm,
236
+ ),
237
+ ].map((match) => match[1]!)
238
+
239
+ const clangDeclarationEnumCache = new Map<string, string[]>()
240
+ function clangDeclarationEnums(directory: string): string[] {
241
+ const cached = clangDeclarationEnumCache.get(directory)
242
+ if (cached) return cached
243
+ const enums = readdirSync(directory)
244
+ .filter((file) => file.endsWith('.h'))
245
+ .flatMap((file) => objcEnumerations(readFileSync(path.join(directory, file), 'utf8')))
246
+ clangDeclarationEnumCache.set(directory, enums)
247
+ return enums
248
+ }
249
+
250
+ export const objcEnumForward = /^[ \t]*SWIFT_ENUM_FWD_DECL\s*\(\s*\w+\s*,\s*(\w+)\b/
251
+
252
+ export function withoutImportedSdkEnumForwards(
253
+ header: string,
254
+ owners: ReadonlyMap<string, string>,
255
+ ): string {
256
+ const imports = new Set([...header.matchAll(/^@import (\w+);$/gm)].map((m) => m[1]!))
257
+ return header
258
+ .split('\n')
259
+ .filter((line) => {
260
+ const name = objcEnumForward.exec(line)?.[1]
261
+ const owner = name && owners.get(name)
262
+ return !owner || !imports.has(owner)
263
+ })
264
+ .join('\n')
265
+ }
266
+
267
+ /** the @_cdecl functions a generated header declares that one of the native header texts also declares. */
268
+ export function nativelyDeclaredFunctions(
269
+ generated: string,
270
+ headers: Iterable<string>,
271
+ ): string[] {
272
+ const candidates = [
273
+ ...new Set(
274
+ [...generated.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
275
+ (match) => match[1]!,
276
+ ),
277
+ ),
278
+ ]
279
+ if (candidates.length === 0) return []
280
+ const declaration = new RegExp(`^[^\\n#/*]*?\\b(${candidates.join('|')})\\s*\\(`, 'gm')
281
+ const found = new Set<string>()
282
+ for (const header of headers)
283
+ for (const match of header.matchAll(declaration)) found.add(match[1]!)
284
+ return [...found]
285
+ }
286
+
287
+ const sdkDeclarationOwners = new Map<string, Map<string, string>>()
288
+ /** the framework whose headers define each Objective-C class, protocol and enumeration in an SDK's frameworks directory. */
289
+ export function sdkObjCDeclarationOwners(frameworks: string): Map<string, string> {
290
+ const known = sdkDeclarationOwners.get(frameworks)
291
+ if (known) return known
292
+ const owners = new Map<string, string>()
293
+ for (const framework of readdirSync(frameworks))
294
+ if (framework.endsWith('.framework')) {
295
+ const headers = path.join(frameworks, framework, 'Headers')
296
+ if (existsSync(headers))
297
+ for (const file of readdirSync(headers, { recursive: true, encoding: 'utf8' }))
298
+ if (file.endsWith('.h')) {
299
+ const header = readFileSync(path.join(headers, file), 'utf8')
300
+ for (const name of [
301
+ ...swiftInterfaceDeclarations(header),
302
+ ...objcEnumerations(header),
303
+ ...[
304
+ ...header.matchAll(/^[A-Z_]*_(?:EXTERN|EXPORT)\b[^;(\n]*?\b(\w+)\s*\(/gm),
305
+ ].map((match) => match[1]!),
306
+ ])
307
+ owners.set(name, framework.slice(0, -'.framework'.length))
308
+ }
309
+ }
310
+ sdkDeclarationOwners.set(frameworks, owners)
311
+ return owners
312
+ }
313
+
314
+ export function swiftHeaderWithSuperclassImports(
315
+ header: string,
316
+ interfaceFor: (
317
+ name: string,
318
+ ) => { file: string; header: string; module: boolean } | null,
319
+ ): string {
320
+ const superclasses = new Set(
321
+ [...header.matchAll(/@interface\s+\w+\s*:\s*(\w+)/g)].map((match) => match[1]!),
322
+ )
323
+ return header.replace(/^@import (\w+);$/gm, (statement, name: string) => {
324
+ const dependency = interfaceFor(name)
325
+ // a framework peach implements only in swift has no clang module to
326
+ // import; its objective-c surface is the generated interface alone
327
+ if (dependency && !dependency.module)
328
+ return `#import ${JSON.stringify(dependency.file)}`
329
+ if (
330
+ !dependency ||
331
+ ![...swiftInterfaceDeclarations(dependency.header)].some((name) =>
332
+ superclasses.has(name),
333
+ )
334
+ )
335
+ return statement
336
+ return `${statement}\n#import ${JSON.stringify(dependency.file)}`
337
+ })
338
+ }
339
+
340
+ /** the Objective-C protocols and classes a generated interface header defines. */
341
+ export const swiftInterfaceDeclarations = (header: string): Set<string> =>
342
+ new Set([
343
+ ...[
344
+ ...header.matchAll(
345
+ /^[ \t]*(?:[A-Z_]\w*(?:\([^()\n]*\))?[ \t]+)*@protocol\s+(\w+)\b(?![^\n]*;\s*$)/gm,
346
+ ),
347
+ ].map((m) => m[1]!),
348
+ ...[
349
+ ...header.matchAll(
350
+ /^[ \t]*(?:[A-Z_]\w*(?:\([^()\n]*\))?[ \t]+)*@interface\s+(\w+)\s*(?=[:<{]|$)/gm,
351
+ ),
352
+ ].map((m) => m[1]!),
353
+ ])
354
+
355
+ /** a header with the definitions Swift owns replaced by an import of its interface header. */
356
+ export function withoutSwiftDeclarations(
357
+ text: string,
358
+ declared: ReadonlySet<string>,
359
+ interfaceImport: string,
360
+ ): string {
361
+ const out: string[] = []
362
+ let skipping: 'objc' | 'enum' | undefined
363
+ let imported = false
364
+ // clang refuses to enter a header inside an assume_nonnull region, so the
365
+ // import goes above the region's start when the declaration sits inside it.
366
+ let regionStart = -1
367
+ for (const line of text.split('\n')) {
368
+ if (skipping) {
369
+ if (skipping === 'objc' ? /^@end\b/.test(line) : /^\s*};/.test(line))
370
+ skipping = undefined
371
+ continue
372
+ }
373
+ if (regionStart < 0 && /^NS_ASSUME_NONNULL_BEGIN\b/.test(line))
374
+ regionStart = out.length
375
+ const name =
376
+ /^\s*(?:[A-Z_]\w*(?:\([^()\n]*\))?\s+)*@(?:protocol|interface)\s+(\w+)\s*(?=[:<{]|$)/.exec(
377
+ line,
378
+ )?.[1]
379
+ // an @_cdecl function the native headers already declare keeps their prototype
380
+ const external = /^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(.*\)[^;\n]*;\s*$/.exec(
381
+ line,
382
+ )?.[1]
383
+ if (external && declared.has(external)) continue
384
+ const enumeration =
385
+ /^\s*typedef\s+(?:NS_ENUM|NS_OPTIONS|SWIFT_ENUM(?:_NAMED)?)\s*\(\s*\w+\s*,\s*(\w+)\b/.exec(
386
+ line,
387
+ )?.[1]
388
+ const enumForward = objcEnumForward.exec(line)?.[1]
389
+ const declaration = name ?? enumeration ?? enumForward
390
+ if (declaration && declared.has(declaration)) {
391
+ skipping = name ? 'objc' : enumeration && !line.includes('};') ? 'enum' : undefined
392
+ // generated Swift annotations belong to the declaration being removed.
393
+ while (
394
+ /^(?:SWIFT_[A-Z_]+|(?:NS|CF)_SWIFT_NAME)(?:\(.*\))?\s*$/.test(out.at(-1) ?? '')
395
+ )
396
+ out.pop()
397
+ if (!imported)
398
+ out.splice(regionStart < 0 ? out.length : regionStart, 0, interfaceImport)
399
+ imported = true
400
+ continue
401
+ }
402
+ out.push(line)
403
+ }
404
+ return out.join('\n')
405
+ }
406
+
407
+ /** the wasm SDK a module root compiles with: a distribution's manifest names
408
+ * it, a source checkout's toolchain.json pins it. */
409
+ export function swiftModuleSdk(root: string): SwiftWasmSdk {
410
+ const pin = swiftDistributionAt(root) ?? swiftSourceSdk(root)
411
+ return {
412
+ wasmSdkId: pin.wasmSdkId,
413
+ wasmSdkUrl: pin.wasmSdkUrl,
414
+ wasmSdkChecksum: pin.wasmSdkChecksum,
415
+ }
416
+ }
417
+
418
+ /** swiftpm's sdk option for a compile against `moduleRoot`: the installed
419
+ * sdk seen through the module root's shared framework headers. */
420
+ export function swiftCompileSdkOptions(
421
+ moduleRoot: string,
422
+ toolchainBin: string,
423
+ ): string[] {
424
+ return swiftSharedSdkViewOptions(
425
+ moduleRoot,
426
+ swiftDistributionAt(moduleRoot) !== null,
427
+ toolchainBin,
428
+ swiftModuleSdk(moduleRoot).wasmSdkId,
429
+ )
430
+ }
431
+
432
+ // toolchain.json is an input for its wasm sdk checksum: the sdk's icu blob,
433
+ // which the host fills into every artifact, is part of what the address names.
434
+ // distribution producers are inputs so repaired builds get a fresh immutable id.
435
+ // a distribution's manifest names every file it ships by digest.
436
+ export function swiftModuleInputFiles(root: string): string[] {
437
+ if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST]
438
+ const files: string[] = [
439
+ ...swiftSharedSdkInputFiles(root),
440
+ '../peachsim/src/swift-shared-sdk.ts',
441
+ '../peachsim/src/swift-runtime-products.ts',
442
+ '../peachsim/src/swiftRuntimeProductContract.ts',
443
+ '../peachsim/src/swiftTargetContract.ts',
444
+ '../peachsim/src/swift-darwin-records.ts',
445
+ '../peachsim/src/swift-uniform-type-constants.ts',
446
+ '../peach-engine/native/core/input/control_tracking.h',
447
+ '../../scripts/generate/swift-sdk-module/darwin-mach.json',
448
+ '../../scripts/generate/swift-sdk-module/darwin-socketvar.json',
449
+ '../../scripts/ops/swift-distribution-publish.ts',
450
+ '../../src/helpers/mapLimit.ts',
451
+ 'Package.swift',
452
+ 'scripts/contrast-app-Package.swift',
453
+ 'scripts/build-distribution.ts',
454
+ 'scripts/runtime-product.ts',
455
+ 'scripts/runtime-product-scopes.ts',
456
+ 'scripts/distribution-runtime-products.ts',
457
+ 'scripts/build-helpers.ts',
458
+ 'scripts/build-cache.ts',
459
+ 'scripts/build-cache-launcher.ts',
460
+ 'scripts/distribution-clang.ts',
461
+ 'runtime/UniformTypeIdentifiersConstants.m',
462
+ 'Sources/libxml2/include/module.modulemap',
463
+ 'Sources/libxml2/COPYING',
464
+ 'scripts/build-distribution-plugins.sh',
465
+ 'scripts/build-distribution-plugins-docker.sh',
466
+ 'scripts/build-preview-plugin.sh',
467
+ 'toolchain.json',
468
+ ]
469
+ const walk = (dir: string) => {
470
+ for (const entry of readdirSync(path.join(root, dir), {
471
+ withFileTypes: true,
472
+ })) {
473
+ const relative = `${dir}/${entry.name}`
474
+ if (entry.isDirectory()) walk(relative)
475
+ else if (
476
+ /\.(swift|swiftinterface|swiftoverlay|c|cpp|h|inc|m|mm|modulemap|apinotes|json)$/.test(
477
+ entry.name,
478
+ )
479
+ )
480
+ files.push(relative)
481
+ }
482
+ }
483
+ walk('Sources')
484
+ walk('cross-import-overlays')
485
+ // the iOS simulator standard library objective-c stand-ins import against
486
+ walk('ios-simulator-stdlib')
487
+ return files.sort()
488
+ }
489
+
490
+ // the host macro plugins build side by side and load explicitly for every
491
+ // app compile. their source inputs also participate in artifact identity.
492
+ /** the host macro plugin libraries a module root compiles with, and whether a
493
+ * checkout's must be rebuilt (scripts/build-preview-plugin.sh) first. */
494
+ export function swiftMacroPlugins(
495
+ moduleRoot: string,
496
+ dir = path.join(moduleRoot, '.build/host/RnxPreviewMacros'),
497
+ ): {
498
+ libraries: string[]
499
+ executables: string[]
500
+ stale: boolean
501
+ } {
502
+ const distribution = swiftDistributionAt(moduleRoot)
503
+ if (distribution) {
504
+ const view = swiftDistributionCompileView(moduleRoot, distribution)
505
+ return {
506
+ libraries: distribution.plugins
507
+ .filter((plugin) => path.basename(plugin) !== 'ExpoModulesMacros')
508
+ .map((plugin) => path.join(view, plugin)),
509
+ executables: distribution.plugins
510
+ .filter((plugin) => path.basename(plugin) === 'ExpoModulesMacros')
511
+ .map((plugin) => path.join(view, plugin)),
512
+ stale: false,
513
+ }
514
+ }
515
+ const release = JSON.parse(
516
+ readFileSync(path.join(moduleRoot, 'toolchain.json'), 'utf8'),
517
+ ).release
518
+ const compilerStamp = path.join(dir, 'compiler-release')
519
+ const pluginScript = path.join(moduleRoot, 'scripts/build-preview-plugin.sh')
520
+ const expoPlugin = path.join(dir, 'ExpoModulesMacros')
521
+ // linux names a plugin's module from lib<Module>.so
522
+ const ext = process.platform === 'darwin' ? 'dylib' : 'so'
523
+ const plugins = [
524
+ {
525
+ library: path.join(dir, `libRnxPreviewMacros.${ext}`),
526
+ sources: [path.join(moduleRoot, 'Sources/RnxPreviewMacros/PreviewMacro.swift')],
527
+ },
528
+ {
529
+ library: path.join(dir, `libFoundationMacros.${ext}`),
530
+ sources: [
531
+ path.join(moduleRoot, 'Sources/FoundationMacros/PredicateMacro.swift'),
532
+ path.join(moduleRoot, 'Sources/SwiftMacroSupport/PredicateExpression.swift'),
533
+ ],
534
+ },
535
+ {
536
+ library: path.join(dir, `libTipKitMacros.${ext}`),
537
+ sources: [
538
+ path.join(moduleRoot, 'Sources/TipKitMacros/TipKitMacros.swift'),
539
+ path.join(moduleRoot, 'Sources/SwiftMacroSupport/PredicateExpression.swift'),
540
+ ],
541
+ },
542
+ ]
543
+ return {
544
+ libraries: plugins.map(({ library }) => library),
545
+ executables: [expoPlugin],
546
+ stale:
547
+ !existsSync(compilerStamp) ||
548
+ !existsSync(expoPlugin) ||
549
+ statSync(pluginScript).mtimeMs > statSync(expoPlugin).mtimeMs ||
550
+ readFileSync(compilerStamp, 'utf8').trim() !== release ||
551
+ plugins.some(
552
+ ({ library, sources }) =>
553
+ !existsSync(library) ||
554
+ sources.some((source) => statSync(source).mtimeMs > statSync(library).mtimeMs),
555
+ ),
556
+ }
557
+ }
558
+
559
+ const linkedModuleDigests = new Map<string, { stamp: string; digest: Buffer }>()
560
+
561
+ export function clearLinkedModuleDigests(root?: string): void {
562
+ if (root === undefined) linkedModuleDigests.clear()
563
+ else linkedModuleDigests.delete(root)
564
+ }
565
+
566
+ // a clean git worktree shares the exact same source bytes as any other worktree
567
+ // on the same tree/blob OIDs. hashing the git OIDs avoids reading 14k+ files on
568
+ // every fresh worktree while still falling back to full reads on any dirty input.
569
+ function gitCleanModuleInputsKey(root: string, files: readonly string[]): string | null {
570
+ if (swiftDistributionAt(root)) return null
571
+ const top = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], {
572
+ encoding: 'utf8',
573
+ stdio: ['ignore', 'pipe', 'ignore'],
574
+ })
575
+ if (top.status !== 0) return null
576
+ const repoTop = top.stdout.trim()
577
+ if (!repoTop) return null
578
+ const realTop = realpathSync(repoTop)
579
+ const realRoot = realpathSync(root)
580
+ const collapsedDirs = [
581
+ path.join(realRoot, 'Sources'),
582
+ path.join(realRoot, 'cross-import-overlays'),
583
+ path.join(realRoot, 'ios-simulator-stdlib'),
584
+ realpathSync(path.resolve(realRoot, '../peachsim/sdk/ios')),
585
+ ]
586
+ const scoped = new Set<string>()
587
+ for (const dir of collapsedDirs) {
588
+ const rel = path.relative(realTop, dir).split(path.sep).join('/')
589
+ if (!rel || rel.startsWith('../')) return null
590
+ scoped.add(rel)
591
+ }
592
+ for (const file of files) {
593
+ const full = path.resolve(realRoot, file)
594
+ if (collapsedDirs.some((dir) => full.startsWith(dir + path.sep))) continue
595
+ const rel = path.relative(realTop, full).split(path.sep).join('/')
596
+ if (!rel || rel.startsWith('../')) return null
597
+ scoped.add(rel)
598
+ }
599
+ const paths = [...scoped].sort()
600
+ const status = spawnSync(
601
+ 'git',
602
+ [
603
+ '-C',
604
+ realTop,
605
+ 'status',
606
+ '--porcelain',
607
+ '--untracked-files=all',
608
+ '--ignored=matching',
609
+ '--',
610
+ ...paths,
611
+ ],
612
+ {
613
+ encoding: 'utf8',
614
+ stdio: ['ignore', 'pipe', 'ignore'],
615
+ maxBuffer: 16 * 1024 * 1024,
616
+ },
617
+ )
618
+ if (status.status !== 0 || status.stdout.trim().length > 0) return null
619
+ const oids = spawnSync(
620
+ 'git',
621
+ ['-C', realTop, 'rev-parse', ...paths.map((entry) => `HEAD:${entry}`)],
622
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
623
+ )
624
+ if (oids.status !== 0) return null
625
+ const keyHash = createHash('sha256')
626
+ keyHash.update('git-module-digest/v1\n')
627
+ keyHash.update(oids.stdout)
628
+ keyHash.update('\n')
629
+ for (const file of files) keyHash.update(file).update('\n')
630
+ return keyHash.digest('hex')
631
+ }
632
+
633
+ /** the digest of a module checkout's inputs: what an artifact address and a
634
+ * distribution's id name it by. */
635
+ export function swiftModuleDigest(root: string): Buffer {
636
+ const files = swiftModuleInputFiles(root)
637
+ const stampHash = createHash('sha256')
638
+ for (const file of files) {
639
+ const stat = statSync(path.join(root, file), { bigint: true })
640
+ stampHash.update(file)
641
+ stampHash.update(
642
+ `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}\n`,
643
+ )
644
+ }
645
+ const stamp = stampHash.digest('hex')
646
+ const cached = linkedModuleDigests.get(root)
647
+ if (cached?.stamp === stamp) return cached.digest
648
+ // a source checkout holds thousands of inputs, so a fresh bridge reuses the
649
+ // digest an earlier process recorded under the same stamp.
650
+ const digestDir = path.join(swiftCacheDir(), 'swift-module-digests')
651
+ const record = path.join(
652
+ digestDir,
653
+ `${createHash('sha256').update(root).digest('hex')}.json`,
654
+ )
655
+ const writeRecord = (target: string, body: string) => {
656
+ mkdirSync(path.dirname(target), { recursive: true })
657
+ const partial = `${target}.${process.pid}.${randomUUID()}`
658
+ writeFileSync(partial, body)
659
+ renameSync(partial, target)
660
+ }
661
+ if (existsSync(record)) {
662
+ const saved: unknown = JSON.parse(readFileSync(record, 'utf8'))
663
+ if (
664
+ saved &&
665
+ typeof saved === 'object' &&
666
+ Reflect.get(saved, 'stamp') === stamp &&
667
+ typeof Reflect.get(saved, 'digest') === 'string'
668
+ ) {
669
+ const digest = Buffer.from(String(Reflect.get(saved, 'digest')), 'hex')
670
+ linkedModuleDigests.set(root, { stamp, digest })
671
+ return digest
672
+ }
673
+ }
674
+ const gitKey = gitCleanModuleInputsKey(root, files)
675
+ const gitRecord = gitKey ? path.join(digestDir, `git-${gitKey}.json`) : null
676
+ if (gitRecord && existsSync(gitRecord)) {
677
+ const saved: unknown = JSON.parse(readFileSync(gitRecord, 'utf8'))
678
+ if (
679
+ saved &&
680
+ typeof saved === 'object' &&
681
+ typeof Reflect.get(saved, 'digest') === 'string'
682
+ ) {
683
+ const hex = String(Reflect.get(saved, 'digest'))
684
+ const digest = Buffer.from(hex, 'hex')
685
+ linkedModuleDigests.set(root, { stamp, digest })
686
+ writeRecord(record, JSON.stringify({ stamp, digest: hex }))
687
+ return digest
688
+ }
689
+ }
690
+ const hash = createHash('sha256')
691
+ for (const file of files) {
692
+ hash.update(createHash('sha256').update(file).digest())
693
+ hash.update(
694
+ createHash('sha256')
695
+ .update(readFileSync(path.join(root, file)))
696
+ .digest(),
697
+ )
698
+ }
699
+ const digest = hash.digest()
700
+ const hex = digest.toString('hex')
701
+ linkedModuleDigests.set(root, { stamp, digest })
702
+ writeRecord(record, JSON.stringify({ stamp, digest: hex }))
703
+ if (gitRecord) writeRecord(gitRecord, JSON.stringify({ digest: hex }))
704
+ return digest
705
+ }
706
+
707
+ const compileSurfaces = new WeakMap<SwiftDistributionManifest, Buffer>()
708
+
709
+ /**
710
+ * the digest of what a compile against a module root reads. a distribution's
711
+ * objects reach only a link, so distributions that differ in function bodies
712
+ * alone share every product compiled against either.
713
+ */
714
+ export function swiftCompileSurfaceDigest(root: string): Buffer {
715
+ const distribution = swiftDistributionAt(root)
716
+ if (!distribution) return swiftModuleDigest(root)
717
+ let digest = compileSurfaces.get(distribution)
718
+ if (!digest) {
719
+ digest = createHash('sha256')
720
+ .update(
721
+ JSON.stringify([
722
+ distribution.release,
723
+ distribution.wasmSdkId,
724
+ distribution.wasmSdkChecksum,
725
+ distribution.modules,
726
+ distribution.plugins,
727
+ distribution.link,
728
+ Object.entries(distribution.files)
729
+ .filter(([file]) => !file.startsWith('lib/'))
730
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),
731
+ ]),
732
+ )
733
+ .digest()
734
+ compileSurfaces.set(distribution, digest)
735
+ }
736
+ return digest
737
+ }
738
+
739
+ // an import may carry attributes (`@_exported`, `@preconcurrency`) and a
740
+ // declaration kind (`import struct Nuke.ImageRequest`).
741
+ export const SWIFT_IMPORT =
742
+ /^\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_]*)/
743
+
744
+ // three-valued (kleene) logic shared by the swift and c condition
745
+ // evaluators: an undecided operand only decides when the other forces the
746
+ // outcome, so false && undefined is false and true || undefined is true.
747
+ export const kleeneNot = (value: boolean | undefined): boolean | undefined =>
748
+ value === undefined ? undefined : !value
749
+ export const kleeneAnd = (
750
+ left: boolean | undefined,
751
+ right: boolean | undefined,
752
+ ): boolean | undefined =>
753
+ left === false || right === false
754
+ ? false
755
+ : left === true && right === true
756
+ ? true
757
+ : undefined
758
+ export const kleeneOr = (
759
+ left: boolean | undefined,
760
+ right: boolean | undefined,
761
+ ): boolean | undefined =>
762
+ left === true || right === true
763
+ ? true
764
+ : left === false && right === false
765
+ ? false
766
+ : undefined
767
+
768
+ // a compilation condition as the wasm compile sees it after the source
769
+ // rewrite below: `os(iOS)` holds, other platforms (WASI too) do not,
770
+ // `canImport` holds for an available module. what the scan cannot know
771
+ // (custom flags, swift versions, features) is undefined, three-valued
772
+ // through `!`, `&&` and `||`.
773
+ export const NON_IOS_MODULES = new Set(['FoundationNetworking', 'WASILibc'])
774
+
775
+ function swiftCondition(
776
+ text: string,
777
+ available?: ReadonlySet<string>,
778
+ defines?: ReadonlySet<string>,
779
+ ): boolean | undefined {
780
+ const tokens = text.match(/\w+\s*\([^()]*\)|&&|\|\||!|\(|\)|\w+/g) ?? []
781
+ let index = 0
782
+ const atom = (): boolean | undefined => {
783
+ const token = tokens[index++]
784
+ if (token === '!') return kleeneNot(atom())
785
+ if (token === '(') {
786
+ const value = either()
787
+ index++
788
+ return value
789
+ }
790
+ if (token === 'true') return true
791
+ if (token === 'false') return false
792
+ // with the target's full -D set known, swift reads any other name as false.
793
+ if (defines && /^[A-Za-z_]\w*$/.test(token ?? '')) return defines.has(token!)
794
+ const call = /^(\w+)\s*\(\s*([^,()]*?)\s*(?:,[^()]*)?\)$/.exec(token ?? '')
795
+ if (!call) return undefined
796
+ const [, name, argument] = call
797
+ if (name === 'os') return argument === 'iOS'
798
+ if (name === 'canImport')
799
+ return !NON_IOS_MODULES.has(argument!) && available?.has(argument!)
800
+ if (name === 'targetEnvironment') return argument === 'simulator'
801
+ if (name === 'arch') return argument === 'wasm64' || argument === 'arm64'
802
+ return undefined
803
+ }
804
+ const both = (): boolean | undefined => {
805
+ let value = atom()
806
+ while (tokens[index] === '&&') {
807
+ index++
808
+ value = kleeneAnd(value, atom())
809
+ }
810
+ return value
811
+ }
812
+ const either = (): boolean | undefined => {
813
+ let value = both()
814
+ while (tokens[index] === '||') {
815
+ index++
816
+ value = kleeneOr(value, both())
817
+ }
818
+ return value
819
+ }
820
+ return either()
821
+ }
822
+
823
+ // each line's branch state under the app's wasm compilation conditions.
824
+ // directives themselves are not executable source. the scan reads code, never
825
+ // content: an `import` or directive inside a string literal or comment is
826
+ // template text, not source (a dependency's code template once reported its
827
+ // `import Cocoa` line as a missing module).
828
+ export function* swiftConditionalLines(
829
+ contents: string,
830
+ available?: ReadonlySet<string>,
831
+ defines?: ReadonlySet<string>,
832
+ ): Generator<{ line: string; active: boolean | undefined }> {
833
+ // per open `#if`: whether its current branch is active, and whether an
834
+ // earlier branch was taken (or may have been)
835
+ const frames: { active: boolean | undefined; taken: boolean | undefined }[] = []
836
+ for (const line of swiftCodeMask(contents).split('\n')) {
837
+ const directive = /^\s*#(if|elseif|else|endif)\b(.*)$/.exec(line)
838
+ if (directive) {
839
+ const [, kind, rest] = directive
840
+ const condition = (rest ?? '').replace(/\/\/.*$/, '').trim()
841
+ if (kind === 'if') {
842
+ const active = swiftCondition(condition, available, defines)
843
+ frames.push({ active, taken: active })
844
+ } else if (kind === 'endif') frames.pop()
845
+ else if (frames.length > 0) {
846
+ const frame = frames[frames.length - 1]!
847
+ const holds =
848
+ kind === 'else' ? true : swiftCondition(condition, available, defines)
849
+ frame.active =
850
+ frame.taken === true
851
+ ? false
852
+ : frame.taken === false
853
+ ? holds
854
+ : holds && undefined
855
+ frame.taken =
856
+ frame.taken === true || holds === true
857
+ ? true
858
+ : frame.taken === false
859
+ ? holds
860
+ : undefined
861
+ }
862
+ yield { line, active: false }
863
+ continue
864
+ }
865
+ yield {
866
+ line,
867
+ active: frames.some((frame) => frame.active === false)
868
+ ? false
869
+ : frames.every((frame) => frame.active === true)
870
+ ? true
871
+ : undefined,
872
+ }
873
+ }
874
+ }
875
+
876
+ /**
877
+ * the modules a source imports, in order. with `available`, only imports the
878
+ * wasm compile certainly reaches: those outside every `#if`, or in a branch
879
+ * whose condition holds there, `os(iOS)` included since the compile rewrites
880
+ * it to true. a branch the scan cannot decide may compile out, so its
881
+ * imports stay out of the list.
882
+ */
883
+ const importNamesCache = new Map<string, string[]>()
884
+
885
+ export function swiftImportNames(
886
+ contents: string,
887
+ available?: ReadonlySet<string>,
888
+ ): string[] {
889
+ if (available === undefined) {
890
+ const cached = importNamesCache.get(contents)
891
+ if (cached !== undefined) return cached
892
+ }
893
+ const names: string[] = []
894
+ for (const { line, active } of swiftConditionalLines(contents, available)) {
895
+ if (available && active !== true) continue
896
+ const name = SWIFT_IMPORT.exec(line)?.[1]
897
+ if (name) names.push(name)
898
+ }
899
+ if (available === undefined) importNamesCache.set(contents, names)
900
+ return names
901
+ }
902
+
903
+ /**
904
+ * the modules peach itself provides at `moduleRoot`: a distribution lists
905
+ * them, a checkout's manifest declares them as targets.
906
+ */
907
+ export function swiftPeachModules(moduleRoot: string): string[] {
908
+ const distribution = swiftDistributionAt(moduleRoot)
909
+ return distribution
910
+ ? distribution.modules
911
+ : swiftManifestDeclarations(
912
+ readFileSync(path.join(moduleRoot, 'Package.swift'), 'utf8'),
913
+ )
914
+ .filter((target) => !target.executable && !target.path.startsWith('fixtures/'))
915
+ .map((target) => target.name)
916
+ }
917
+
918
+ const sdkPaths = new Map<
919
+ string,
920
+ {
921
+ sysroot: string
922
+ darwin: string
923
+ resources: string
924
+ frameworks: string[]
925
+ cFlags: string[]
926
+ }
927
+ >()
928
+
929
+ /** the wasm SDK's sysroot, swift resource directory, and clang intake.
930
+ * raw swiftc does not read the toolset, so stand-in compiles pass cFlags. */
931
+ export function swiftSdkPaths(
932
+ moduleRoot: string,
933
+ toolchainBin: string,
934
+ options = swiftCompileSdkOptions(moduleRoot, toolchainBin),
935
+ ): {
936
+ sysroot: string
937
+ darwin: string
938
+ resources: string
939
+ frameworks: string[]
940
+ cFlags: string[]
941
+ } {
942
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId
943
+ const key = JSON.stringify([toolchainBin, sdk, options])
944
+ const cached = sdkPaths.get(key)
945
+ if (cached) return cached
946
+ const configuration = execFileSync(
947
+ path.join(toolchainBin, 'swift'),
948
+ ['sdk', 'configure', ...options, '--show-configuration', sdk, SWIFT_WASM_TRIPLE],
949
+ { encoding: 'utf8', env: swiftEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] },
950
+ )
951
+ const field = (name: string) => {
952
+ const value = new RegExp(`^${name}:\\s*(.+)$`, 'm').exec(configuration)?.[1]?.trim()
953
+ if (!value) throw new Error(`swift sdk ${sdk} reports no ${name}`)
954
+ return value
955
+ }
956
+ const sysroot = field('sdkRootPath')
957
+ // clang flags from the toolset's swift driver. -fwasm-exceptions is omitted:
958
+ // it selects the wasm exception model and aborts unless -Xllvm
959
+ // -wasm-enable-eh is also passed, and symbolgraph-extract has no -Xllvm.
960
+ const cFlags: string[] = []
961
+ const frameworks: string[] = []
962
+ const configuredToolsets = field('toolsetPaths')
963
+ if (configuredToolsets !== 'not set') {
964
+ const toolsets: unknown = JSON.parse(configuredToolsets)
965
+ if (!Array.isArray(toolsets) || !toolsets.every((value) => typeof value === 'string'))
966
+ throw new Error(`swift sdk ${sdk} reports invalid toolset paths`)
967
+ for (const toolset of toolsets) {
968
+ const config: unknown = JSON.parse(readFileSync(toolset, 'utf8'))
969
+ if (!config || typeof config !== 'object' || !('swiftCompiler' in config)) continue
970
+ const compiler = config.swiftCompiler
971
+ if (!compiler || typeof compiler !== 'object' || !('extraCLIOptions' in compiler))
972
+ continue
973
+ const options = compiler.extraCLIOptions
974
+ if (!Array.isArray(options) || !options.every((value) => typeof value === 'string'))
975
+ throw new Error(
976
+ `swift sdk ${sdk} has invalid swift compiler options in ${toolset}`,
977
+ )
978
+ for (let index = 0; index < options.length; index++) {
979
+ if (options[index] === '-Xcc' && typeof options[index + 1] === 'string') {
980
+ const flag = options[index + 1]
981
+ if (flag !== '-fwasm-exceptions') cFlags.push(flag)
982
+ if (
983
+ flag === '-iframeworkwithsysroot' &&
984
+ options[index + 2] === '-Xcc' &&
985
+ typeof options[index + 3] === 'string'
986
+ ) {
987
+ cFlags.push(options[index + 3])
988
+ frameworks.push(path.join(sysroot, options[index + 3]))
989
+ index += 3
990
+ continue
991
+ }
992
+ index += 1
993
+ continue
994
+ }
995
+ const option = options[index]
996
+ if (option.startsWith('-iframework') || option.startsWith('-F'))
997
+ throw new Error(
998
+ `swift sdk ${sdk} has an unsupported framework search option ${option}`,
999
+ )
1000
+ }
1001
+ }
1002
+ }
1003
+ const paths = {
1004
+ sysroot,
1005
+ darwin: path.join(sysroot, 'darwin'),
1006
+ resources: field('swiftResourcesPath'),
1007
+ frameworks,
1008
+ cFlags,
1009
+ }
1010
+ sdkPaths.set(key, paths)
1011
+ return paths
1012
+ }
1013
+
1014
+ // the guest implements native Foundation's exports in several modules.
1015
+ export const FOUNDATION_IMPLICIT_MODULES = [
1016
+ 'PeachObjC',
1017
+ 'Dispatch',
1018
+ 'FoundationNetworking',
1019
+ 'PeachFoundationCombine',
1020
+ 'Darwin',
1021
+ ]
1022
+ const FRAMEWORK_COMPANION_IMPORT =
1023
+ /^[ \t]*((?:(?:@\w+(?:\([^)]*\))?|public|package|internal|fileprivate|private)[ \t]+)*)import[ \t]+(Foundation|UIKit|SwiftUI|Photos|CoreData|SystemConfiguration|Dispatch)[ \t]*;?[ \t]*$/
1024
+
1025
+ export function withFrameworkCompanionImports(source: string): string {
1026
+ const original = source.split('\n')
1027
+ const imports: string[] = []
1028
+ let hasCompanions = false
1029
+ for (const [index, line] of swiftCodeMask(source).split('\n').entries()) {
1030
+ const conditional = /#(?:(?:if|elseif)\b.*|(?:else|endif)\b)/.exec(line)
1031
+ if (conditional) {
1032
+ const start = conditional.index
1033
+ imports.push(original[index]!.slice(start, start + conditional[0].length))
1034
+ continue
1035
+ }
1036
+ const matched = FRAMEWORK_COMPANION_IMPORT.exec(line.trimEnd())
1037
+ if (!matched) continue
1038
+ const [, attributes = '', framework] = matched
1039
+ const modifiers: string[] =
1040
+ attributes.match(
1041
+ /@(?:preconcurrency|_exported|_implementationOnly)\b|\b(?:public|package|internal|fileprivate|private)\b/g,
1042
+ ) ?? []
1043
+ const preconcurrency = modifiers.includes('@preconcurrency')
1044
+ const modules =
1045
+ framework === 'SystemConfiguration'
1046
+ ? ['Dispatch', 'Darwin']
1047
+ : framework === 'Dispatch'
1048
+ ? ['PeachFoundationCombine']
1049
+ : preconcurrency
1050
+ ? ['CoreFoundation', 'ObjectiveC', ...FOUNDATION_IMPLICIT_MODULES]
1051
+ : FOUNDATION_IMPLICIT_MODULES
1052
+ const prefix = modifiers.length ? modifiers.join(' ') + ' ' : ''
1053
+ imports.push(...modules.map((module) => `${prefix}import ${module}`))
1054
+ if (framework === 'Foundation' && modifiers.includes('public'))
1055
+ imports.push(
1056
+ '@_exported public import protocol Combine.ObservableObject',
1057
+ '@_exported public import struct Combine.Published',
1058
+ )
1059
+ if (framework === 'CoreData')
1060
+ imports.push(
1061
+ `${prefix}import protocol Combine.ObservableObject`,
1062
+ `${prefix}import struct Combine.Published`,
1063
+ )
1064
+ hasCompanions = true
1065
+ }
1066
+ if (!hasCompanions) return source
1067
+ // mirror conditional imports without shifting the original source locations.
1068
+ return `${source}${source.endsWith('\n') ? '' : '\n'}#if canImport(PeachObjC)\n${imports.join('\n')}\n#endif\n`
1069
+ }
1070
+
1071
+ // one compile masks each source in several scans; the cache holds a bounded
1072
+ // number of characters and forgets everything when full.
1073
+ const codeMasks = new Map<string, string>()
1074
+ let codeMaskChars = 0
1075
+ const CODE_MASK_CACHE_CHARS = 256 * 1024 * 1024
1076
+
1077
+ export function swiftCodeMask(source: string): string {
1078
+ const cached = codeMasks.get(source)
1079
+ if (cached !== undefined) return cached
1080
+ const masked = maskSwiftCode(source)
1081
+ if (codeMaskChars + source.length > CODE_MASK_CACHE_CHARS) {
1082
+ codeMasks.clear()
1083
+ importNamesCache.clear()
1084
+ codeMaskChars = 0
1085
+ }
1086
+ codeMasks.set(source, masked)
1087
+ codeMaskChars += source.length
1088
+ return masked
1089
+ }
1090
+
1091
+ function maskSwiftCode(source: string): string {
1092
+ const chars = source.split('')
1093
+ const blank = (from: number, to: number): void => {
1094
+ for (let i = Math.max(0, from); i < Math.min(to, chars.length); i++)
1095
+ if (chars[i] !== '\n') chars[i] = ' '
1096
+ }
1097
+ const hashesAt = (at: number): number => {
1098
+ let end = at
1099
+ while (source[end] === '#') end++
1100
+ return end - at
1101
+ }
1102
+ const scanString = (quote: number, hashes: number): number => {
1103
+ const multiline = source.startsWith('"""', quote)
1104
+ let i = quote + (multiline ? 3 : 1)
1105
+ const keep: [number, number][] = []
1106
+ const quoteEnd = (at: number): boolean => {
1107
+ const mark = multiline ? '"""' : '"'
1108
+ return (
1109
+ source.startsWith(mark, at) &&
1110
+ source.startsWith('#'.repeat(hashes), at + mark.length)
1111
+ )
1112
+ }
1113
+ while (i < chars.length) {
1114
+ if (source[i] === '\\' && source.startsWith('#'.repeat(hashes), i + 1)) {
1115
+ const escaped = i + 1 + hashes
1116
+ if (source[escaped] === '(') {
1117
+ const codeStart = escaped + 1
1118
+ const codeEnd = scanCode(codeStart, true)
1119
+ keep.push([codeStart, codeEnd])
1120
+ i = codeEnd + 1
1121
+ } else {
1122
+ i = escaped + 1
1123
+ }
1124
+ continue
1125
+ }
1126
+ if (quoteEnd(i)) {
1127
+ const close = i + (multiline ? 3 : 1) + hashes
1128
+ let cursor = quote - hashes
1129
+ const ranges: [number, number][] = [...keep, [close, close]]
1130
+ for (const [from, to] of ranges)
1131
+ if (from > cursor) {
1132
+ blank(cursor, from)
1133
+ cursor = to
1134
+ } else cursor = Math.max(cursor, to)
1135
+ return close
1136
+ }
1137
+ i++
1138
+ }
1139
+ blank(quote - hashes, chars.length)
1140
+ return chars.length
1141
+ }
1142
+ // an interpolation's `)` ends the scan only when no paren is open inside
1143
+ const scanCode = (i: number, nested: boolean): number => {
1144
+ let parens = 0
1145
+ while (i < chars.length) {
1146
+ const char = source[i]!
1147
+ if (char === '/' && source[i + 1] === '/') {
1148
+ const end = source.indexOf('\n', i)
1149
+ blank(i, end === -1 ? chars.length : end)
1150
+ i = end === -1 ? chars.length : end
1151
+ continue
1152
+ }
1153
+ if (char === '/' && source[i + 1] === '*') {
1154
+ let j = i + 2
1155
+ let depth = 1
1156
+ while (j < chars.length && depth > 0) {
1157
+ if (source.startsWith('/*', j)) {
1158
+ depth++
1159
+ j += 2
1160
+ } else if (source.startsWith('*/', j)) {
1161
+ depth--
1162
+ j += 2
1163
+ } else j++
1164
+ }
1165
+ blank(i, j)
1166
+ i = j
1167
+ continue
1168
+ }
1169
+ if (char === '#') {
1170
+ const hashes = hashesAt(i)
1171
+ const at = i + hashes
1172
+ if (source[at] === '"') {
1173
+ i = scanString(at, hashes)
1174
+ continue
1175
+ }
1176
+ if (hashes > 0 && source[at] === '/') {
1177
+ const mark = '#'.repeat(hashes)
1178
+ let j = at + 1
1179
+ while (
1180
+ j < chars.length &&
1181
+ !(source[j] === '/' && source.startsWith(mark, j + 1))
1182
+ )
1183
+ j++
1184
+ blank(i, Math.min(chars.length, j + 1 + hashes))
1185
+ i = Math.min(chars.length, j + 1 + hashes)
1186
+ continue
1187
+ }
1188
+ i++
1189
+ continue
1190
+ }
1191
+ if (char === '"') {
1192
+ i = scanString(i, 0)
1193
+ continue
1194
+ }
1195
+ if (char === '(') parens++
1196
+ else if (char === ')') {
1197
+ if (nested && parens === 0) return i
1198
+ parens--
1199
+ }
1200
+ i++
1201
+ }
1202
+ return i
1203
+ }
1204
+ scanCode(0, false)
1205
+ return chars.join('')
1206
+ }
1207
+
1208
+ // darwin declares these in Foundation; the guest networking module owns them.
1209
+ export const FOUNDATION_NETWORKING_TYPES = new Set([
1210
+ 'NSURLConnection',
1211
+ 'NSURLConnectionDataDelegate',
1212
+ 'NSURLConnectionDelegate',
1213
+ 'NSURLConnectionDownloadDelegate',
1214
+ ])
1215
+
1216
+ // Foundation overlay declarations live in the shared guest overlay module.
1217
+ export const FOUNDATION_OVERLAY_TYPES = new Set([
1218
+ 'AsyncCharacterSequence',
1219
+ 'AsyncLineSequence',
1220
+ 'AsyncUnicodeScalarSequence',
1221
+ 'BlockOperation',
1222
+ 'DateComponentsFormatter',
1223
+ 'ErrorUserInfoKey',
1224
+ 'ListFormatter',
1225
+ 'LocalizedStringResource',
1226
+ 'MachError',
1227
+ 'MeasurementFormatUnitUsage',
1228
+ 'MessagePort',
1229
+ 'NSAssertionHandler',
1230
+ 'NSAttributedStringFormattingContextKey',
1231
+ 'NSBundleResourceRequest',
1232
+ 'NSConditionLock',
1233
+ 'NSException',
1234
+ 'NSExtensionItem',
1235
+ 'NSFastEnumerationIterator',
1236
+ 'NSFastEnumerationState',
1237
+ 'NSFileAccessIntent',
1238
+ 'NSFileManagerResumeSyncBehavior',
1239
+ 'NSFileManagerSupportedSyncControls',
1240
+ 'NSFileManagerUploadLocalVersionConflictPolicy',
1241
+ 'NSFileProviderService',
1242
+ 'NSFileProviderServiceName',
1243
+ 'NSFileSecurity',
1244
+ 'NSGrammaticalCase',
1245
+ 'NSGrammaticalDefiniteness',
1246
+ 'NSGrammaticalDetermination',
1247
+ 'NSGrammaticalGender',
1248
+ 'NSGrammaticalNumber',
1249
+ 'NSGrammaticalPartOfSpeech',
1250
+ 'NSGrammaticalPerson',
1251
+ 'NSGrammaticalPronounType',
1252
+ 'NSHashEnumerator',
1253
+ 'NSHashTable',
1254
+ 'NSHashTableCallBacks',
1255
+ 'NSKeyValueOperator',
1256
+ 'NSKeyValueSetMutationKind',
1257
+ 'NSKeyValueSharedObservers',
1258
+ // clang Foundation owns the linguistic tagger types. A Swift twin is ambiguous with the header.
1259
+ 'NSMachPort',
1260
+ 'NSMapEnumerator',
1261
+ 'NSMapTable',
1262
+ 'NSMapTableKeyCallBacks',
1263
+ 'NSMapTableValueCallBacks',
1264
+ 'NSMetadataItem',
1265
+ 'NSMetadataQuery',
1266
+ 'NSMetadataQueryAttributeValueTuple',
1267
+ 'NSMetadataQueryDelegate',
1268
+ 'NSMetadataQueryResultGroup',
1269
+ 'NSPointerArray',
1270
+ 'NSPredicateValidating',
1271
+ 'NSProxy',
1272
+ 'NSPurgeableData',
1273
+ 'NSSecureUnarchiveFromDataTransformer',
1274
+ 'NSUbiquitousKeyValueStore',
1275
+ 'NSXPCCoder',
1276
+ 'NSXPCConnection',
1277
+ 'NSXPCInterface',
1278
+ 'NSXPCListener',
1279
+ 'NSXPCListenerDelegate',
1280
+ 'NSXPCListenerEndpoint',
1281
+ 'OperationQueue',
1282
+ 'PredicateCodableConfiguration',
1283
+ 'PresentationIntent',
1284
+ 'SocketPort',
1285
+ 'StringEncodingDetectionOptionsKey',
1286
+ 'TermOfAddress',
1287
+ 'URLFileProtection',
1288
+ 'URLResource',
1289
+ 'URLUbiquitousItemDownloadingStatus',
1290
+ 'URLUbiquitousSharedItemPermissions',
1291
+ 'URLUbiquitousSharedItemRole',
1292
+ 'ValueTransformer',
1293
+ ])
1294
+
1295
+ // existing overlay globals retain their declaration and runtime owner.
1296
+ export const FOUNDATION_OVERLAY_GLOBALS = new Set([
1297
+ 'CFBridgingRetain',
1298
+ 'NSAllHashTableObjects',
1299
+ 'NSAllMapTableKeys',
1300
+ 'NSAllMapTableValues',
1301
+ 'NSAllocateMemoryPages',
1302
+ 'NSAssertionHandlerKey',
1303
+ 'NSBuddhistCalendar',
1304
+ 'NSBundleResourceRequestLoadingPriorityUrgent',
1305
+ 'NSChineseCalendar',
1306
+ 'NSCompareHashTables',
1307
+ 'NSCompareMapTables',
1308
+ 'NSCopyMemoryPages',
1309
+ 'NSCountHashTable',
1310
+ 'NSCountMapTable',
1311
+ 'NSCreateHashTable',
1312
+ 'NSCreateMapTable',
1313
+ 'NSDeallocateMemoryPages',
1314
+ 'NSEndHashTableEnumeration',
1315
+ 'NSEndMapTableEnumeration',
1316
+ 'NSEnumerateHashTable',
1317
+ 'NSEnumerateMapTable',
1318
+ 'NSExtensionItemAttachmentsKey',
1319
+ 'NSExtensionItemAttributedContentTextKey',
1320
+ 'NSExtensionItemAttributedTitleKey',
1321
+ 'NSExtensionItemsAndErrorsKey',
1322
+ 'NSExtensionJavaScriptFinalizeArgumentKey',
1323
+ 'NSExtensionJavaScriptPreprocessingResultsKey',
1324
+ 'NSFreeHashTable',
1325
+ 'NSFreeMapTable',
1326
+ 'NSGetUncaughtExceptionHandler',
1327
+ 'NSGregorianCalendar',
1328
+ 'NSHashGet',
1329
+ 'NSHashInsert',
1330
+ 'NSHashInsertIfAbsent',
1331
+ 'NSHashInsertKnownAbsent',
1332
+ 'NSHashRemove',
1333
+ 'NSHebrewCalendar',
1334
+ 'NSISO8601Calendar',
1335
+ 'NSIndianCalendar',
1336
+ 'NSIslamicCalendar',
1337
+ 'NSIslamicCivilCalendar',
1338
+ 'NSItemProviderPreferredImageSizeKey',
1339
+ 'NSJapaneseCalendar',
1340
+ 'NSLoadedClasses',
1341
+ 'NSLocalizedFailureErrorKey',
1342
+ 'NSLogPageSize',
1343
+ 'NSMACHOperatingSystem',
1344
+ 'NSMapGet',
1345
+ 'NSMapInsert',
1346
+ 'NSMapInsertIfAbsent',
1347
+ 'NSMapInsertKnownAbsent',
1348
+ 'NSMapMember',
1349
+ 'NSMapRemove',
1350
+ 'NSMultipleUnderlyingErrorsKey',
1351
+ 'NSNextHashEnumeratorItem',
1352
+ 'NSNextMapEnumeratorPair',
1353
+ 'NSNonOwnedPointerHashCallBacks',
1354
+ 'NSNonOwnedPointerMapKeyCallBacks',
1355
+ 'NSNonOwnedPointerMapValueCallBacks',
1356
+ 'NSNonOwnedPointerOrNullMapKeyCallBacks',
1357
+ 'NSNonRetainedObjectHashCallBacks',
1358
+ 'NSNonRetainedObjectMapKeyCallBacks',
1359
+ 'NSNonRetainedObjectMapValueCallBacks',
1360
+ 'NSObjectHashCallBacks',
1361
+ 'NSObjectMapKeyCallBacks',
1362
+ 'NSObjectMapValueCallBacks',
1363
+ 'NSOpenStepRootDirectory',
1364
+ 'NSOwnedObjectIdentityHashCallBacks',
1365
+ 'NSOwnedPointerHashCallBacks',
1366
+ 'NSOwnedPointerMapKeyCallBacks',
1367
+ 'NSOwnedPointerMapValueCallBacks',
1368
+ 'NSPersianCalendar',
1369
+ 'NSPointerToStructHashCallBacks',
1370
+ 'NSPropertyListErrorMaximum',
1371
+ 'NSPropertyListErrorMinimum',
1372
+ 'NSRepublicOfChinaCalendar',
1373
+ 'NSResetHashTable',
1374
+ 'NSResetMapTable',
1375
+ 'NSSolarisOperatingSystem',
1376
+ 'NSStringFromHashTable',
1377
+ 'NSStringFromMapTable',
1378
+ 'NSSunOSOperatingSystem',
1379
+ 'NSTextCheckingAllCustomTypes',
1380
+ 'NSTextCheckingAllSystemTypes',
1381
+ 'NSTextCheckingAllTypes',
1382
+ 'NSURLAuthenticationMethodHTMLForm',
1383
+ 'NSURLAuthenticationMethodNTLM',
1384
+ 'NSURLAuthenticationMethodNegotiate',
1385
+ 'NSURLCredentialStorageRemoveSynchronizableCredentials',
1386
+ 'NSURLErrorFileOutsideSafeArea',
1387
+ 'NSURLProtectionSpaceFTP',
1388
+ 'NSURLProtectionSpaceFTPProxy',
1389
+ 'NSURLProtectionSpaceHTTP',
1390
+ 'NSURLProtectionSpaceHTTPProxy',
1391
+ 'NSURLProtectionSpaceHTTPS',
1392
+ 'NSURLProtectionSpaceHTTPSProxy',
1393
+ 'NSURLProtectionSpaceSOCKSProxy',
1394
+ 'NSURLSessionUploadTaskResumeData',
1395
+ 'NSUbiquitousFileErrorMaximum',
1396
+ 'NSUbiquitousFileErrorMinimum',
1397
+ 'NSUbiquitousKeyValueStoreAccountChange',
1398
+ 'NSUbiquitousKeyValueStoreChangeReasonKey',
1399
+ 'NSUbiquitousKeyValueStoreChangedKeysKey',
1400
+ 'NSUbiquitousKeyValueStoreInitialSyncChange',
1401
+ 'NSUbiquitousKeyValueStoreQuotaViolationChange',
1402
+ 'NSUbiquitousKeyValueStoreServerChange',
1403
+ 'NSUndoCloseGroupingRunLoopOrdering',
1404
+ 'NSUndoManagerGroupIsDiscardableKey',
1405
+ 'NSUserActivityErrorMaximum',
1406
+ 'NSUserActivityErrorMinimum',
1407
+ 'NSValidationErrorMaximum',
1408
+ 'NSValidationErrorMinimum',
1409
+ 'NSWindows95OperatingSystem',
1410
+ 'NSWindowsNTOperatingSystem',
1411
+ 'NSWrapCalendarComponents',
1412
+ 'NSXPCConnectionCodeSigningRequirementFailure',
1413
+ 'NSXPCConnectionErrorMaximum',
1414
+ 'NSXPCConnectionErrorMinimum',
1415
+ 'kCFStringEncodingASCII',
1416
+ ])
1417
+
1418
+ export const CORE_FOUNDATION_OVERLAY_GLOBALS = new Set([
1419
+ 'kCFCoreFoundationVersionNumber10_0',
1420
+ 'kCFCoreFoundationVersionNumber10_0_3',
1421
+ 'kCFCoreFoundationVersionNumber10_1',
1422
+ 'kCFCoreFoundationVersionNumber10_10',
1423
+ 'kCFCoreFoundationVersionNumber10_10_1',
1424
+ 'kCFCoreFoundationVersionNumber10_10_2',
1425
+ 'kCFCoreFoundationVersionNumber10_10_3',
1426
+ 'kCFCoreFoundationVersionNumber10_10_4',
1427
+ 'kCFCoreFoundationVersionNumber10_10_5',
1428
+ 'kCFCoreFoundationVersionNumber10_10_Max',
1429
+ 'kCFCoreFoundationVersionNumber10_11',
1430
+ 'kCFCoreFoundationVersionNumber10_11_1',
1431
+ 'kCFCoreFoundationVersionNumber10_11_2',
1432
+ 'kCFCoreFoundationVersionNumber10_11_3',
1433
+ 'kCFCoreFoundationVersionNumber10_11_4',
1434
+ 'kCFCoreFoundationVersionNumber10_11_Max',
1435
+ 'kCFCoreFoundationVersionNumber10_1_1',
1436
+ 'kCFCoreFoundationVersionNumber10_1_2',
1437
+ 'kCFCoreFoundationVersionNumber10_1_3',
1438
+ 'kCFCoreFoundationVersionNumber10_1_4',
1439
+ 'kCFCoreFoundationVersionNumber10_2',
1440
+ 'kCFCoreFoundationVersionNumber10_2_1',
1441
+ 'kCFCoreFoundationVersionNumber10_2_2',
1442
+ 'kCFCoreFoundationVersionNumber10_2_3',
1443
+ 'kCFCoreFoundationVersionNumber10_2_4',
1444
+ 'kCFCoreFoundationVersionNumber10_2_5',
1445
+ 'kCFCoreFoundationVersionNumber10_2_6',
1446
+ 'kCFCoreFoundationVersionNumber10_2_7',
1447
+ 'kCFCoreFoundationVersionNumber10_2_8',
1448
+ 'kCFCoreFoundationVersionNumber10_3',
1449
+ 'kCFCoreFoundationVersionNumber10_3_1',
1450
+ 'kCFCoreFoundationVersionNumber10_3_2',
1451
+ 'kCFCoreFoundationVersionNumber10_3_3',
1452
+ 'kCFCoreFoundationVersionNumber10_3_4',
1453
+ 'kCFCoreFoundationVersionNumber10_3_5',
1454
+ 'kCFCoreFoundationVersionNumber10_3_6',
1455
+ 'kCFCoreFoundationVersionNumber10_3_7',
1456
+ 'kCFCoreFoundationVersionNumber10_3_8',
1457
+ 'kCFCoreFoundationVersionNumber10_3_9',
1458
+ 'kCFCoreFoundationVersionNumber10_4',
1459
+ 'kCFCoreFoundationVersionNumber10_4_1',
1460
+ 'kCFCoreFoundationVersionNumber10_4_10',
1461
+ 'kCFCoreFoundationVersionNumber10_4_11',
1462
+ 'kCFCoreFoundationVersionNumber10_4_2',
1463
+ 'kCFCoreFoundationVersionNumber10_4_3',
1464
+ 'kCFCoreFoundationVersionNumber10_4_4_Intel',
1465
+ 'kCFCoreFoundationVersionNumber10_4_4_PowerPC',
1466
+ 'kCFCoreFoundationVersionNumber10_4_5_Intel',
1467
+ 'kCFCoreFoundationVersionNumber10_4_5_PowerPC',
1468
+ 'kCFCoreFoundationVersionNumber10_4_6_Intel',
1469
+ 'kCFCoreFoundationVersionNumber10_4_6_PowerPC',
1470
+ 'kCFCoreFoundationVersionNumber10_4_7',
1471
+ 'kCFCoreFoundationVersionNumber10_4_8',
1472
+ 'kCFCoreFoundationVersionNumber10_4_9',
1473
+ 'kCFCoreFoundationVersionNumber10_5',
1474
+ 'kCFCoreFoundationVersionNumber10_5_1',
1475
+ 'kCFCoreFoundationVersionNumber10_5_2',
1476
+ 'kCFCoreFoundationVersionNumber10_5_3',
1477
+ 'kCFCoreFoundationVersionNumber10_5_4',
1478
+ 'kCFCoreFoundationVersionNumber10_5_5',
1479
+ 'kCFCoreFoundationVersionNumber10_5_6',
1480
+ 'kCFCoreFoundationVersionNumber10_5_7',
1481
+ 'kCFCoreFoundationVersionNumber10_5_8',
1482
+ 'kCFCoreFoundationVersionNumber10_6',
1483
+ 'kCFCoreFoundationVersionNumber10_6_1',
1484
+ 'kCFCoreFoundationVersionNumber10_6_2',
1485
+ 'kCFCoreFoundationVersionNumber10_6_3',
1486
+ 'kCFCoreFoundationVersionNumber10_6_4',
1487
+ 'kCFCoreFoundationVersionNumber10_6_5',
1488
+ 'kCFCoreFoundationVersionNumber10_6_6',
1489
+ 'kCFCoreFoundationVersionNumber10_6_7',
1490
+ 'kCFCoreFoundationVersionNumber10_6_8',
1491
+ 'kCFCoreFoundationVersionNumber10_7',
1492
+ 'kCFCoreFoundationVersionNumber10_7_1',
1493
+ 'kCFCoreFoundationVersionNumber10_7_2',
1494
+ 'kCFCoreFoundationVersionNumber10_7_3',
1495
+ 'kCFCoreFoundationVersionNumber10_7_4',
1496
+ 'kCFCoreFoundationVersionNumber10_7_5',
1497
+ 'kCFCoreFoundationVersionNumber10_8',
1498
+ 'kCFCoreFoundationVersionNumber10_8_1',
1499
+ 'kCFCoreFoundationVersionNumber10_8_2',
1500
+ 'kCFCoreFoundationVersionNumber10_8_3',
1501
+ 'kCFCoreFoundationVersionNumber10_8_4',
1502
+ 'kCFCoreFoundationVersionNumber10_9',
1503
+ 'kCFCoreFoundationVersionNumber10_9_1',
1504
+ 'kCFCoreFoundationVersionNumber10_9_2',
1505
+ 'kCFCoreFoundationVersionNumber_iOS_4_0',
1506
+ 'kCFCoreFoundationVersionNumber_iOS_4_1',
1507
+ 'kCFCoreFoundationVersionNumber_iOS_4_2',
1508
+ 'kCFCoreFoundationVersionNumber_iOS_4_3',
1509
+ 'kCFCoreFoundationVersionNumber_iOS_5_0',
1510
+ 'kCFCoreFoundationVersionNumber_iOS_5_1',
1511
+ 'kCFCoreFoundationVersionNumber_iOS_6_0',
1512
+ 'kCFCoreFoundationVersionNumber_iOS_6_1',
1513
+ 'kCFCoreFoundationVersionNumber_iOS_7_0',
1514
+ 'kCFCoreFoundationVersionNumber_iOS_7_1',
1515
+ 'kCFCoreFoundationVersionNumber_iOS_8_0',
1516
+ 'kCFCoreFoundationVersionNumber_iOS_8_1',
1517
+ 'kCFCoreFoundationVersionNumber_iOS_8_2',
1518
+ 'kCFCoreFoundationVersionNumber_iOS_8_3',
1519
+ 'kCFCoreFoundationVersionNumber_iOS_8_4',
1520
+ 'kCFCoreFoundationVersionNumber_iOS_8_x_Max',
1521
+ 'kCFCoreFoundationVersionNumber_iOS_9_0',
1522
+ 'kCFCoreFoundationVersionNumber_iOS_9_1',
1523
+ 'kCFCoreFoundationVersionNumber_iOS_9_2',
1524
+ 'kCFCoreFoundationVersionNumber_iOS_9_3',
1525
+ 'kCFCoreFoundationVersionNumber_iOS_9_4',
1526
+ 'kCFCoreFoundationVersionNumber_iOS_9_x_Max',
1527
+ 'kCFCoreFoundationVersionNumber_iPhoneOS_2_0',
1528
+ 'kCFCoreFoundationVersionNumber_iPhoneOS_2_1',
1529
+ 'kCFCoreFoundationVersionNumber_iPhoneOS_2_2',
1530
+ 'kCFCoreFoundationVersionNumber_iPhoneOS_3_0',
1531
+ 'kCFCoreFoundationVersionNumber_iPhoneOS_3_1',
1532
+ 'kCFCoreFoundationVersionNumber_iPhoneOS_3_2',
1533
+ ])
1534
+
1535
+ // the guest module that owns a name darwin's Foundation declares
1536
+ export function foundationOwnerOf(name: string): string | undefined {
1537
+ if (name === 'NSKeyValueObservedChange' || name === 'NSKeyValueObservation')
1538
+ return 'PeachObjC'
1539
+ if (name === 'DispatchData') return 'Dispatch'
1540
+ if (FOUNDATION_NETWORKING_TYPES.has(name)) return 'FoundationNetworking'
1541
+ if (
1542
+ FOUNDATION_OVERLAY_TYPES.has(name) ||
1543
+ FOUNDATION_OVERLAY_GLOBALS.has(name) ||
1544
+ CORE_FOUNDATION_OVERLAY_GLOBALS.has(name)
1545
+ )
1546
+ return 'PeachFoundation'
1547
+ return undefined
1548
+ }
1549
+
1550
+ /** the macro environment a c-family entry guard evaluates against. */
1551
+ export interface SwiftCMacroEnvironment {
1552
+ /** the target's -D set, with values where given. */
1553
+ defines: ReadonlyMap<string, string | undefined>
1554
+ /** the compiler's own predefines for the unit's language. */
1555
+ predefines: ReadonlyMap<string, string | undefined>
1556
+ /** names any of the target's own sources or headers defines. */
1557
+ targetDefined: ReadonlySet<string>
1558
+ }
1559
+
1560
+ export const emptyMacroEnvironment: SwiftCMacroEnvironment = {
1561
+ defines: new Map(),
1562
+ predefines: new Map(),
1563
+ targetDefined: new Set(),
1564
+ }
1565
+
1566
+ // whether the environment defines the name: -D and predefines decide,
1567
+ // a name only the target's own sources define is undecided (order and
1568
+ // conditions are not evaluated), and a name nowhere visible is absent.
1569
+ function cMacroDefined(name: string, env: SwiftCMacroEnvironment): boolean | undefined {
1570
+ if (env.defines.has(name) || env.predefines.has(name)) return true
1571
+ if (env.targetDefined.has(name)) return undefined
1572
+ return false
1573
+ }
1574
+
1575
+ function cMacroIntOrTrue(value: string | undefined): boolean | undefined {
1576
+ if (value === undefined) return true
1577
+ if (/^0[xX][0-9a-fA-F]+[uUlL]*$/.test(value) || /^\d+[uUlL]*$/.test(value))
1578
+ return Number.parseInt(value) !== 0
1579
+ return undefined
1580
+ }
1581
+
1582
+ function cMacroBareValue(name: string, env: SwiftCMacroEnvironment): boolean | undefined {
1583
+ if (env.defines.has(name)) return cMacroIntOrTrue(env.defines.get(name))
1584
+ if (env.predefines.has(name)) return cMacroIntOrTrue(env.predefines.get(name))
1585
+ if (env.targetDefined.has(name)) return undefined
1586
+ return false
1587
+ }
1588
+
1589
+ function cMacroNegated(name: string, env: SwiftCMacroEnvironment): boolean | undefined {
1590
+ return kleeneNot(cMacroDefined(name, env))
1591
+ }
1592
+
1593
+ // a preprocessor condition the macro environment decides, or undefined when
1594
+ // the text needs the real preprocessor (comparisons, function-like macros,
1595
+ // __has_include and the like). only defined-ness, boolean operators and
1596
+ // integer literals evaluate; the rest is undecided.
1597
+ function cConditionValue(
1598
+ expression: string,
1599
+ env: SwiftCMacroEnvironment,
1600
+ ): boolean | undefined {
1601
+ let i = 0
1602
+ const skipSpaces = () => {
1603
+ while (i < expression.length && /\s/.test(expression[i]!)) i++
1604
+ }
1605
+ const parseOr = (): boolean | undefined => {
1606
+ let value = parseAnd()
1607
+ for (;;) {
1608
+ skipSpaces()
1609
+ if (!expression.startsWith('||', i)) return value
1610
+ i += 2
1611
+ value = kleeneOr(value, parseAnd())
1612
+ }
1613
+ }
1614
+ const parseAnd = (): boolean | undefined => {
1615
+ let value = parseUnary()
1616
+ for (;;) {
1617
+ skipSpaces()
1618
+ if (!expression.startsWith('&&', i)) return value
1619
+ i += 2
1620
+ value = kleeneAnd(value, parseUnary())
1621
+ }
1622
+ }
1623
+ const parseUnary = (): boolean | undefined => {
1624
+ skipSpaces()
1625
+ if (expression[i] === '!') {
1626
+ i++
1627
+ return kleeneNot(parseUnary())
1628
+ }
1629
+ if (expression[i] === '(') {
1630
+ i++
1631
+ const value = parseOr()
1632
+ skipSpaces()
1633
+ return expression[i] === ')' ? (i++, value) : undefined
1634
+ }
1635
+ const defined = /^defined\b/.exec(expression.slice(i))
1636
+ if (defined) {
1637
+ i += defined[0].length
1638
+ skipSpaces()
1639
+ const parenthesized = expression[i] === '('
1640
+ if (parenthesized) {
1641
+ i++
1642
+ skipSpaces()
1643
+ }
1644
+ const name = /^\w+/.exec(expression.slice(i))?.[0]
1645
+ if (!name) return undefined
1646
+ i += name.length
1647
+ skipSpaces()
1648
+ if (parenthesized) {
1649
+ if (expression[i] !== ')') return undefined
1650
+ i++
1651
+ }
1652
+ return cMacroDefined(name, env)
1653
+ }
1654
+ const literal = /^(0[xX][0-9a-fA-F]+|\d+)[uUlL]*/.exec(expression.slice(i))
1655
+ if (literal) {
1656
+ i += literal[0].length
1657
+ return Number(literal[1]) !== 0
1658
+ }
1659
+ const name = /^\w+/.exec(expression.slice(i))?.[0]
1660
+ if (!name) return undefined
1661
+ i += name.length
1662
+ return cMacroBareValue(name, env)
1663
+ }
1664
+ const value = parseOr()
1665
+ skipSpaces()
1666
+ return i === expression.length ? value : undefined
1667
+ }
1668
+
1669
+ // the lines xcode's preprocessor keeps: conditional directives evaluated
1670
+ // against the macro environment, with undecided branches kept, so an entry
1671
+ // guard the text cannot decide still counts.
1672
+ export function cActiveCode(code: string, env: SwiftCMacroEnvironment): string {
1673
+ const kept: string[] = []
1674
+ const stack: { parent: boolean; taken: boolean }[] = []
1675
+ let active = true
1676
+ for (const line of code.replace(/\\\r?\n/g, '').split('\n')) {
1677
+ const directive =
1678
+ /^\s*#\s*(if|ifdef|ifndef|elif|elifdef|elifndef|else|endif)\b(.*)$/.exec(line)
1679
+ if (!directive) {
1680
+ if (active) kept.push(line)
1681
+ continue
1682
+ }
1683
+ const keyword = directive[1]!
1684
+ const rest = directive[2]!.trim()
1685
+ if (keyword === 'if' || keyword === 'ifdef' || keyword === 'ifndef') {
1686
+ const name = /^\w+$/.exec(rest)?.[0]
1687
+ const value =
1688
+ keyword === 'if'
1689
+ ? cConditionValue(rest, env)
1690
+ : name === undefined
1691
+ ? undefined
1692
+ : keyword === 'ifdef'
1693
+ ? cMacroDefined(name, env)
1694
+ : cMacroNegated(name, env)
1695
+ stack.push({ parent: active, taken: value === true })
1696
+ active = active && value !== false
1697
+ } else if (keyword === 'endif') {
1698
+ active = stack.pop()?.parent ?? true
1699
+ } else if (stack.length === 0) {
1700
+ continue
1701
+ } else {
1702
+ const frame = stack[stack.length - 1]!
1703
+ if (keyword === 'else') {
1704
+ active = frame.parent && !frame.taken
1705
+ frame.taken = true
1706
+ } else {
1707
+ const name = /^\w+$/.exec(rest)?.[0]
1708
+ const value =
1709
+ keyword === 'elif'
1710
+ ? cConditionValue(rest, env)
1711
+ : name === undefined
1712
+ ? undefined
1713
+ : keyword === 'elifdef'
1714
+ ? cMacroDefined(name, env)
1715
+ : cMacroNegated(name, env)
1716
+ const branch = !frame.taken && value !== false
1717
+ if (branch && value === true) frame.taken = true
1718
+ active = frame.parent && branch
1719
+ }
1720
+ }
1721
+ }
1722
+ return kept.join('\n')
1723
+ }
1724
+
1725
+ // the source with comments and string and character literals removed,
1726
+ // newlines kept so directive lines stay intact.
1727
+ export function stripCCode(source: string): string {
1728
+ let code = ''
1729
+ let i = 0
1730
+ while (i < source.length) {
1731
+ if (source.startsWith('//', i)) {
1732
+ const end = source.indexOf('\n', i)
1733
+ i = end === -1 ? source.length : end
1734
+ } else if (source.startsWith('/*', i)) {
1735
+ const end = source.indexOf('*/', i + 2)
1736
+ i = end === -1 ? source.length : end + 2
1737
+ } else if (source[i] === '"' || source[i] === "'") {
1738
+ const quote = source[i]!
1739
+ i++
1740
+ while (i < source.length && source[i] !== quote) i += source[i] === '\\' ? 2 : 1
1741
+ i++
1742
+ } else {
1743
+ code += source[i]
1744
+ i++
1745
+ }
1746
+ }
1747
+ return code
1748
+ }
1749
+
1750
+ // whether the unit's wasm code takes its own return address, which
1751
+ // the WebAssembly backend rejects ("hasn't implemented __builtin_return_address"):
1752
+ // native machine code the target has no lowering for, like assembly. branches
1753
+ // the native architecture macros guard are not wasm code.
1754
+ export const wasmMacroEnvironment: SwiftCMacroEnvironment = {
1755
+ ...emptyMacroEnvironment,
1756
+ defines: new Map([
1757
+ ['__wasm__', '1'],
1758
+ ['__wasm64__', '1'],
1759
+ ['__wasi__', '1'],
1760
+ ]),
1761
+ }
1762
+ export function swiftCTakesReturnAddress(source: string): boolean {
1763
+ if (!source.includes('__builtin_return_address')) return false
1764
+ return /\b__builtin_return_address\s*\(/.test(
1765
+ cActiveCode(stripCCode(source), wasmMacroEnvironment),
1766
+ )
1767
+ }
1768
+
1769
+ // every name the given sources define. order and conditions are not
1770
+ // evaluated: a name defined anywhere makes its guards undecided.
1771
+ export function swiftCDefinedNames(sources: Iterable<string>): Set<string> {
1772
+ const names = new Set<string>()
1773
+ for (const source of sources)
1774
+ for (const line of stripCCode(source).split('\n')) {
1775
+ const name = /^\s*#\s*define\s+([A-Za-z_]\w*)/.exec(line)?.[1]
1776
+ if (name) names.add(name)
1777
+ }
1778
+ return names
1779
+ }
1780
+
1781
+ /** the host compiler selected by a module root, without requiring a guest SDK. */
1782
+ export function swiftModuleCompiler(root: string): {
1783
+ release: string
1784
+ toolchainBin: string
1785
+ } {
1786
+ const pin: { release: string } =
1787
+ swiftDistributionAt(root) ??
1788
+ JSON.parse(readFileSync(path.join(root, 'toolchain.json'), 'utf8'))
1789
+ return {
1790
+ release: pin.release,
1791
+ toolchainBin: swiftCompiler(pin.release),
1792
+ }
1793
+ }
1794
+
1795
+ /** the release a module root was built for and its installed toolchain. */
1796
+ export function swiftModuleToolchain(root: string): {
1797
+ release: string
1798
+ toolchainBin: string
1799
+ } {
1800
+ const { release } = swiftModuleCompiler(root)
1801
+ return { release, toolchainBin: swiftToolchain(release, swiftModuleSdk(root)) }
1802
+ }
1803
+
1804
+ export function remoteSwiftCheckouts(root: string): string {
1805
+ const key = createHash('sha256').update(realpathSync(root)).digest('hex').slice(0, 32)
1806
+ mkdirSync(cacheDir(), { recursive: true })
1807
+ return path.join(realpathSync(cacheDir()), 'swift-packages', key, 'checkouts')
1808
+ }
1809
+
1810
+ export const swiftBinaryOnDisk = (binary: { url: string | null; dir: string }): boolean =>
1811
+ binary.url !== null || existsSync(binary.dir)