peachsim 0.1.773 → 0.1.774

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 (72) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/agent-identity.cjs +1 -1
  4. package/dist-lib/agent-sessions.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 +1 -1
  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 +1 -1
  13. package/dist-lib/bridge-contract.cjs +1 -1
  14. package/dist-lib/bridge-contract.mjs +1 -1
  15. package/dist-lib/capture-contract.cjs +1 -1
  16. package/dist-lib/capture-contract.mjs +1 -1
  17. package/dist-lib/cli-constants.cjs +1 -1
  18. package/dist-lib/cloud-contract.cjs +1 -1
  19. package/dist-lib/cloud-contract.mjs +1 -1
  20. package/dist-lib/cloud-test-args.cjs +1 -1
  21. package/dist-lib/cloud-test-args.mjs +1 -1
  22. package/dist-lib/cloud.cjs +1 -1
  23. package/dist-lib/cloud.mjs +1 -1
  24. package/dist-lib/config.cjs +1 -1
  25. package/dist-lib/detox/index.cjs +1 -1
  26. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  27. package/dist-lib/home-paths.cjs +1 -1
  28. package/dist-lib/host/bridge-host.cjs +8 -3
  29. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  30. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  31. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  32. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  33. package/dist-lib/host/websocket-proxy.cjs +1 -1
  34. package/dist-lib/index.cjs +1 -1
  35. package/dist-lib/jump-to-source-babel.cjs +1 -1
  36. package/dist-lib/jump-to-source-native.cjs +1 -1
  37. package/dist-lib/kotlin-host.cjs +1 -1
  38. package/dist-lib/menu.cjs +1 -1
  39. package/dist-lib/menu.mjs +1 -1
  40. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  41. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  42. package/dist-lib/metro-production-bundle.cjs +1 -1
  43. package/dist-lib/metro-production-bundle.mjs +1 -1
  44. package/dist-lib/metro.cjs +1 -1
  45. package/dist-lib/native-app-identity.cjs +1 -1
  46. package/dist-lib/native-app-identity.mjs +1 -1
  47. package/dist-lib/native-firebase-metadata.cjs +1 -1
  48. package/dist-lib/native-firebase-metadata.mjs +1 -1
  49. package/dist-lib/plist.cjs +1 -1
  50. package/dist-lib/plist.mjs +1 -1
  51. package/dist-lib/profiles.cjs +1 -1
  52. package/dist-lib/public-brand.cjs +1 -1
  53. package/dist-lib/react-native-host-modules.cjs +1 -1
  54. package/dist-lib/react-native-host-modules.mjs +1 -1
  55. package/dist-lib/render-mode.cjs +1 -1
  56. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  57. package/dist-lib/sdk.cjs +1 -1
  58. package/dist-lib/sdk.mjs +1 -1
  59. package/dist-lib/skills.cjs +8 -3
  60. package/dist-lib/swift-compile.cjs +7 -2
  61. package/dist-lib/swift-compile.mjs +7 -2
  62. package/dist-lib/swift-package.cjs +1 -1
  63. package/dist-lib/swift-package.mjs +1 -1
  64. package/dist-lib/swift-submit.cjs +1 -1
  65. package/dist-lib/swift-submit.mjs +1 -1
  66. package/dist-lib/swift-toolchain.cjs +1 -1
  67. package/dist-lib/swift.cjs +1 -1
  68. package/dist-lib/vite-swift.cjs +7 -2
  69. package/dist-lib/vite.cjs +1 -1
  70. package/package.json +1 -1
  71. package/src/swift-compile.ts +6 -1
  72. package/src/swift-standin-emit.ts +619 -0
package/dist-lib/vite.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.773 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.774 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  let __sootsim_import_meta_url = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peachsim",
3
- "version": "0.1.773",
3
+ "version": "0.1.774",
4
4
  "description": "Vite and Metro plugins, testing drivers, and SDK exports for peach.",
5
5
  "author": "Tamagui LLC",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -259,13 +259,18 @@ const OPTIONAL_FRAMEWORK_DEPENDENCIES: Record<string, string[]> = {
259
259
  TikTokBusinessSDK: [],
260
260
  nSure: [],
261
261
  Statsig: [],
262
+ RiveRuntime: ['MetalKit'],
263
+ MetalKit: [],
262
264
  DatadogCore: [],
263
265
  DatadogLogs: ['DatadogCore'],
264
266
  DatadogRUM: ['DatadogCore'],
265
267
  DatadogTrace: ['DatadogCore'],
266
268
  AppLovinSDK: [],
267
269
  AppsFlyerLib: [],
268
- FBSDKCoreKit: [],
270
+ FBSDKCoreKit: ['FBAEMKit', 'FBSDKCoreKit_Basics'],
271
+ FBAEMKit: ['FBSDKCoreKit_Basics'],
272
+ FBSDKCoreKit_Basics: [],
273
+ Intercom: [],
269
274
  FBAudienceNetwork: [],
270
275
  }
271
276
  const OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES))
@@ -0,0 +1,619 @@
1
+ // a compile-ready stand-in for a binary swift module peach cannot link: every
2
+ // public declaration its symbol graphs carry, spelled as the sdk spells them,
3
+ // with bodies that trap naming the symbol. nothing succeeds that the sdk did
4
+ // not: storing initializers assign, enum and option raw values come from the
5
+ // caller (read off the sdk, never guessed), and everything else traps. the
6
+ // graphs are swift-symbolgraph-extract output for the module (objective-c
7
+ // modules extract as their swift view), main graph plus `Module@Other`
8
+ // extension graphs. behavior a hand file measures enters as `behavior`:
9
+ // a body, a setter, or a stored property for one declaration path, so the
10
+ // declarations stay the sdk's and only those bodies stop trapping.
11
+
12
+ export type SymbolFragment = { kind: string; spelling: string }
13
+ export type GraphSymbol = {
14
+ kind: { identifier: string }
15
+ identifier: { precise: string }
16
+ pathComponents: string[]
17
+ declarationFragments?: SymbolFragment[]
18
+ accessLevel: string
19
+ availability?: { domain?: string; isUnconditionallyUnavailable?: boolean; obsoleted?: unknown }[]
20
+ }
21
+ export type GraphRelationship = {
22
+ kind: string
23
+ source: string
24
+ target: string
25
+ targetFallback?: string
26
+ }
27
+ export type SymbolGraph = {
28
+ module: { name: string }
29
+ symbols: GraphSymbol[]
30
+ relationships: GraphRelationship[]
31
+ }
32
+
33
+ export type StandinOptions = {
34
+ /** the module being stood in for, e.g. AppLovinSDK. */
35
+ module: string
36
+ /** where the declarations came from, for the banner: sdk, version, artifact. */
37
+ source: string
38
+ /** modules the source imports beside Foundation and UIKit. */
39
+ imports?: string[]
40
+ /** precise symbol id → swift literal for enum cases and option values. */
41
+ values?: ReadonlyMap<string, string>
42
+ /** measured behavior by declaration path (Type.member(label:)). */
43
+ behavior?: ReadonlyMap<string, StandinBehavior>
44
+ /** modules whose protocols a declaration may conform to, beside its own. */
45
+ family?: string[]
46
+ /** paths left out, with why: the compiler rejected their declaration. */
47
+ omit?: ReadonlyMap<string, string>
48
+ /** paths the graph says override but the compiler finds nothing to override */
49
+ plain?: ReadonlySet<string>
50
+ }
51
+
52
+ export type StandinBehavior = {
53
+ /** statements for a function, initializer, or getter body */
54
+ body?: string
55
+ /** statements for a setter body */
56
+ set?: string
57
+ /** a stored property instead of a computed one, with this initial value */
58
+ stored?: string
59
+ }
60
+
61
+ export type StandinResult = {
62
+ source: string
63
+ skipped: { path: string; reason: string }[]
64
+ /** the declaration path that produced each 1-based source line */
65
+ owners: string[]
66
+ }
67
+
68
+ const TYPE_KINDS = new Set([
69
+ 'swift.class',
70
+ 'swift.struct',
71
+ 'swift.enum',
72
+ 'swift.protocol',
73
+ 'swift.typealias',
74
+ ])
75
+ const MEMBER_KINDS = new Set([
76
+ 'swift.method',
77
+ 'swift.type.method',
78
+ 'swift.func.op',
79
+ 'swift.init',
80
+ 'swift.property',
81
+ 'swift.type.property',
82
+ 'swift.subscript',
83
+ 'swift.type.subscript',
84
+ ])
85
+ const ACCESSORS = /\{\s*get(\s+async)?(\s+throws)?(\s+set)?\s*\}\s*$/
86
+ // standard protocols a declaration keeps when the graph names them directly;
87
+ // anything else from outside the family drops with a reason (a missing
88
+ // capability, never a trap).
89
+ const KEEP_EXTERNAL = new Map([
90
+ ['s:SH', 'Hashable'],
91
+ ['s:SQ', 'Equatable'],
92
+ ['s:s5ErrorP', 'Error'],
93
+ ['s:s8SendableP', 'Sendable'],
94
+ ['s:s12IdentifiableP', 'Identifiable'],
95
+ ['s:SY', 'RawRepresentable'],
96
+ ['s:s9OptionSetP', 'OptionSet'],
97
+ ['s:s12CaseIterableP', 'CaseIterable'],
98
+ ['s:SE', 'Encodable'],
99
+ ['s:Se', 'Decodable'],
100
+ ['s:s23CustomStringConvertibleP', 'CustomStringConvertible'],
101
+ ])
102
+ const LEADING_ATTRS = /^((?:@\w+(?:\([^)]*\))?\s*|nonisolated\s+)*)(.*)$/s
103
+
104
+ // objective-c-only attributes and modifiers pure swift cannot spell
105
+ const OBJC_ONLY = /@(?:objcMembers|objc|IBOutlet|IBInspectable|IBAction|IBSegueAction|GKInspectable|nonobjc|NSCopying|NSManaged)(?:\([^)]*\))?\s*|\bdynamic\s+/g
106
+ const text = (symbol: GraphSymbol) =>
107
+ (symbol.declarationFragments ?? [])
108
+ .map((fragment) => fragment.spelling)
109
+ .join('')
110
+ .replace(OBJC_ONLY, '')
111
+ .replace(/(^|\s)optional (?=func|var|init|subscript|static|class)/, '$1')
112
+ const leaf = (symbol: GraphSymbol) => symbol.pathComponents[symbol.pathComponents.length - 1]!
113
+ const pathOf = (symbol: GraphSymbol) => symbol.pathComponents.join('.')
114
+ const unavailable = (symbol: GraphSymbol) =>
115
+ (symbol.availability ?? []).some(
116
+ (entry) => entry.isUnconditionallyUnavailable || entry.obsoleted !== undefined,
117
+ )
118
+ // a witness matches by name and by instance or type side
119
+ const witnessKey = (symbol: GraphSymbol) =>
120
+ `${symbol.kind.identifier.startsWith('swift.type.') ? 'type' : 'instance'}|${leaf(symbol)}`
121
+ const isObjC = (symbol: GraphSymbol) => symbol.identifier.precise.startsWith('c:')
122
+ const trap = (path: string) => `fatalError("${path} is a binary framework peach cannot run")`
123
+
124
+ export function emitSwiftStandin(graphs: SymbolGraph[], options: StandinOptions): StandinResult {
125
+ const skipped: StandinResult['skipped'] = []
126
+ const behavior = options.behavior ?? new Map<string, StandinBehavior>()
127
+ const used = new Set<string>()
128
+ const values = options.values ?? new Map<string, string>()
129
+ const family = new Set([options.module, ...(options.family ?? [])])
130
+ // objective-c imports a completion-handler method twice under one id, the
131
+ // second spelling async; both are declarations.
132
+ const byId = new Map<string, GraphSymbol>()
133
+ const twins = new Map<string, GraphSymbol[]>()
134
+ const owner = new Map<string, string>()
135
+ for (const graph of graphs)
136
+ for (const symbol of graph.symbols) {
137
+ if (symbol.accessLevel !== 'public' && symbol.accessLevel !== 'open') continue
138
+ const id = symbol.identifier.precise
139
+ if (!byId.has(id)) byId.set(id, symbol)
140
+ twins.set(id, [...(twins.get(id) ?? []), symbol])
141
+ }
142
+ const all = (id: string) => twins.get(id) ?? []
143
+ const children = new Map<string, GraphSymbol[]>()
144
+ const superclass = new Map<string, string>()
145
+ const superId = new Map<string, string>()
146
+ const conforms = new Map<string, string[]>()
147
+ const conformIds = new Map<string, string[]>()
148
+ const protocolParents = new Map<string, string[]>()
149
+ const requirement = new Set<string>()
150
+ const optional = new Set<string>()
151
+ const overrides = new Set<string>()
152
+ // extensions of types outside the module, keyed by the extended type name
153
+ const external = new Map<string, GraphSymbol[]>()
154
+ const nameOf = (id: string, fallback?: string) => {
155
+ const local = byId.get(id)
156
+ if (local) return { name: pathOf(local), local: true }
157
+ if (!fallback) return null
158
+ const parts = fallback.split('.')
159
+ return { name: parts.slice(1).join('.') || parts[0]!, module: parts[0]!, local: false }
160
+ }
161
+ for (const graph of graphs)
162
+ for (const edge of graph.relationships) {
163
+ const source = byId.get(edge.source)
164
+ if (!source) continue
165
+ switch (edge.kind) {
166
+ case 'memberOf': {
167
+ const parent = byId.get(edge.target)
168
+ if (parent) {
169
+ owner.set(edge.source, edge.target)
170
+ children.set(edge.target, [...(children.get(edge.target) ?? []), ...all(edge.source)])
171
+ } else if (edge.targetFallback) {
172
+ const name = nameOf(edge.target, edge.targetFallback)!.name
173
+ external.set(name, [...(external.get(name) ?? []), ...all(edge.source)])
174
+ owner.set(edge.source, edge.target)
175
+ }
176
+ break
177
+ }
178
+ case 'inheritsFrom': {
179
+ const target = nameOf(edge.target, edge.targetFallback)
180
+ if (target) superclass.set(edge.source, target.name)
181
+ superId.set(edge.source, edge.target)
182
+ break
183
+ }
184
+ case 'conformsTo': {
185
+ const target = nameOf(edge.target, edge.targetFallback)
186
+ const kept = KEEP_EXTERNAL.get(edge.target)
187
+ const name = kept ?? (target && (target.local || family.has(target.module ?? '')) ? target.name : null)
188
+ if (name) conforms.set(edge.source, [...(conforms.get(edge.source) ?? []), name])
189
+ if (byId.has(edge.target)) {
190
+ const map = source.kind.identifier === 'swift.protocol' ? protocolParents : conformIds
191
+ map.set(edge.source, [...(map.get(edge.source) ?? []), edge.target])
192
+ }
193
+ break
194
+ }
195
+ case 'requirementOf':
196
+ case 'optionalRequirementOf':
197
+ requirement.add(edge.source)
198
+ if (edge.kind === 'optionalRequirementOf') optional.add(edge.source)
199
+ if (byId.has(edge.target) && !owner.has(edge.source)) {
200
+ owner.set(edge.source, edge.target)
201
+ children.set(edge.target, [...(children.get(edge.target) ?? []), ...all(edge.source)])
202
+ }
203
+ break
204
+ case 'overrides':
205
+ overrides.add(edge.source)
206
+ break
207
+ }
208
+ }
209
+
210
+ const lines: string[] = []
211
+ const owners: string[] = []
212
+ const omit = options.omit ?? new Map<string, string>()
213
+ let current = ''
214
+ const emit = (line: string) => {
215
+ lines.push(line)
216
+ owners.push(current)
217
+ }
218
+ // every declaration runs under its own path, so each line names it
219
+ const scoped = <T extends unknown[]>(body: (symbol: GraphSymbol, ...rest: T) => void) =>
220
+ (symbol: GraphSymbol, ...rest: T) => {
221
+ const path = pathOf(symbol)
222
+ if (omit.has(path)) return void skipped.push({ path, reason: omit.get(path)! })
223
+ const previous = current
224
+ current = path
225
+ try {
226
+ body(symbol, ...rest)
227
+ } finally {
228
+ current = previous
229
+ }
230
+ }
231
+
232
+ // members of one owner, unavailable ones and graph twins dropped
233
+ const membersOf = (id: string) => {
234
+ const seen = new Set<string>()
235
+ return (children.get(id) ?? []).filter((member) => {
236
+ if (unavailable(member)) return false
237
+ const key = `${member.kind.identifier}|${text(member)}`
238
+ if (seen.has(key)) return false
239
+ seen.add(key)
240
+ return true
241
+ })
242
+ }
243
+
244
+ const access = (symbol: GraphSymbol, openOwner: boolean) =>
245
+ symbol.accessLevel === 'open' && openOwner ? 'open' : 'public'
246
+
247
+ const emitMember = scoped((
248
+ member: GraphSymbol,
249
+ indent: string,
250
+ context: { openOwner: boolean; inClass: boolean; ownerName: string },
251
+ ) => {
252
+ const path = pathOf(member)
253
+ if (TYPE_KINDS.has(member.kind.identifier)) {
254
+ emitType(member, indent)
255
+ return
256
+ }
257
+ if (member.kind.identifier === 'swift.enum.case') return
258
+ if (!MEMBER_KINDS.has(member.kind.identifier)) {
259
+ skipped.push({ path, reason: `unhandled ${member.kind.identifier}` })
260
+ return
261
+ }
262
+ const { 1: attrs, 2: rest } = LEADING_ATTRS.exec(text(member))!
263
+ const modifiers = /^((?:(?:required|final|override|convenience|unowned(?:\(\w+\))?|weak|lazy|nonisolated|mutating|nonmutating) )*)(.*)$/s.exec(rest!)!
264
+ const flags = new Set(modifiers[1]!.trim().split(/\s+/).filter(Boolean).map((flag) => flag.replace(/\(.*/, '')))
265
+ const required = context.inClass && flags.has('required')
266
+ const final = context.inClass && flags.has('final') ? 'final ' : ''
267
+ const mutating = flags.has('mutating') ? 'mutating ' : flags.has('nonmutating') ? 'nonmutating ' : ''
268
+ let core = `${context.inClass && flags.has('convenience') ? 'convenience ' : ''}${modifiers[2]!}`
269
+ // a class's init() always overrides NSObject's in an objective-c class
270
+ const override =
271
+ context.inClass && !options.plain?.has(path) && (flags.has('override') || overrides.has(member.identifier.precise) || (isObjC(member) && path.endsWith('.init()')))
272
+ ? 'override '
273
+ : ''
274
+ const head = `${indent}${attrs}${access(member, context.openOwner)} ${required ? 'required ' : ''}${final}${override}${mutating}`
275
+ const measured = behavior.get(path)
276
+ if (measured) used.add(path)
277
+ const body = measured?.body ?? trap(path)
278
+ switch (member.kind.identifier) {
279
+ case 'swift.property':
280
+ case 'swift.type.property':
281
+ case 'swift.subscript':
282
+ case 'swift.type.subscript': {
283
+ const accessors = ACCESSORS.exec(core)
284
+ const decl = core.replace(ACCESSORS, '').trimEnd()
285
+ const effects = `${accessors?.[1] ?? ''}${accessors?.[2] ?? ''}`
286
+ const settable = accessors ? Boolean(accessors[3]) : /^(?:static |class )?var /.test(core)
287
+ const computed = decl.replace(/^((?:static |class )*)let /, '$1var ')
288
+ if (measured?.stored !== undefined) {
289
+ // a read-only sdk property stays read-only outside the module
290
+ const ownership = flags.has('weak') ? 'weak ' : flags.has('unowned') ? 'unowned ' : ''
291
+ const setter = settable ? '' : 'internal(set) '
292
+ const value = measured.stored ? ` = ${measured.stored}` : ''
293
+ emit(`${indent}${attrs}${access(member, context.openOwner)} ${setter}${final}${override}${ownership}${computed}${value}`)
294
+ return
295
+ }
296
+ emit(`${head}${computed} { get${effects} { ${body} }${settable && !effects ? ` set { ${measured?.set ?? trap(path)} }` : ''} }`)
297
+ return
298
+ }
299
+ default:
300
+ emit(`${head}${core} { ${body} }`)
301
+ }
302
+ })
303
+
304
+ const header = (symbol: GraphSymbol, keyword: string, indent: string) => {
305
+ const { 1: attrs, 2: rest } = LEADING_ATTRS.exec(text(symbol))!
306
+ const shape = new RegExp(`^(?:final )?${keyword}\\s+\`?(\\w+)\`?(<[^>]*>)?\\s*(?::\\s*([^{]*?))?(\\s+where\\s+.*)?$`).exec(rest!)
307
+ if (!shape) return null
308
+ return { attrs: attrs!, name: shape[1]!, generics: shape[2] ?? '', where: shape[4] ?? '', indent }
309
+ }
310
+
311
+ // the first ancestor outside the module, or null for a root swift class
312
+ const externalRoot = (id: string): string | null => {
313
+ for (let at: string | undefined = id; at; at = superId.get(at)) {
314
+ const next = superId.get(at)
315
+ if (next && !byId.has(next)) return superclass.get(at) ?? null
316
+ }
317
+ return null
318
+ }
319
+ // the graph names a superclass without its generic arguments, and a
320
+ // class under a dropped one cannot compile either.
321
+ const classBlocked = (id: string): string | null => {
322
+ const parent = superId.get(id)
323
+ const parentSymbol = parent ? byId.get(parent) : undefined
324
+ if (!parentSymbol) return null
325
+ if (/^(?:final )?class\s+\w+</.test(LEADING_ATTRS.exec(text(parentSymbol))![2]!))
326
+ return `superclass ${pathOf(parentSymbol)} is generic and the graph omits its arguments`
327
+ if (unavailable(parentSymbol)) return `superclass ${pathOf(parentSymbol)} is unavailable`
328
+ return classBlocked(parent!) && `superclass ${pathOf(parentSymbol)} is left out`
329
+ }
330
+
331
+ const inheritance = (id: string, first?: string) => {
332
+ const list = [...(first ? [first] : []), ...(conforms.get(id) ?? [])]
333
+ return [...new Set(list)]
334
+ }
335
+
336
+ const emitType: (symbol: GraphSymbol, indent: string) => void = scoped((symbol: GraphSymbol, indent: string) => {
337
+ const path = pathOf(symbol)
338
+ const id = symbol.identifier.precise
339
+ const inner = `${indent} `
340
+ switch (symbol.kind.identifier) {
341
+ case 'swift.typealias': {
342
+ const { 1: attrs, 2: rest } = LEADING_ATTRS.exec(text(symbol))!
343
+ emit(`${indent}${attrs}public ${rest}`)
344
+ return
345
+ }
346
+ case 'swift.class': {
347
+ const shape = header(symbol, 'class', indent)
348
+ if (!shape) return void skipped.push({ path, reason: `unparsed class ${text(symbol)}` })
349
+ const parent = superclass.get(id)
350
+ const blocked = classBlocked(id)
351
+ if (blocked) return void skipped.push({ path, reason: blocked })
352
+ // a subclass restates only protocols its ancestors do not already
353
+ // bring; NSObject brings the standard ones.
354
+ const ancestors = new Set<string>()
355
+ for (let at = superId.get(id); at; at = superId.get(at))
356
+ for (const name of conforms.get(at) ?? []) ancestors.add(name)
357
+ const list = [
358
+ ...(parent ? [parent] : []),
359
+ ...(conforms.get(id) ?? []).filter(
360
+ (name) => !ancestors.has(name) && !(parent && [...KEEP_EXTERNAL.values()].includes(name)),
361
+ ),
362
+ ].filter((name, at, all) => all.indexOf(name) === at)
363
+ const parentSymbol = superId.has(id) ? byId.get(superId.get(id)!) : undefined
364
+ const open =
365
+ symbol.accessLevel === 'open' &&
366
+ (!parentSymbol || parentSymbol.accessLevel === 'open')
367
+ emit(`${indent}${shape.attrs}${open ? 'open' : 'public'} class ${shape.name}${shape.generics}${list.length ? `: ${list.join(', ')}` : ''}${shape.where} {`)
368
+ const members = membersOf(id)
369
+ for (const member of members)
370
+ emitMember(member, inner, { openOwner: open, inClass: true, ownerName: shape.name })
371
+ // a class that declares any designated init loses the inherited
372
+ // ones, and a coder-requiring superclass then needs its own.
373
+ const designated = members.some(
374
+ (member) => member.kind.identifier === 'swift.init' && !text(member).startsWith('convenience'),
375
+ )
376
+ // an objective-c class implements its protocols' requirements in the
377
+ // binary without restating them in its header; swift needs a
378
+ // witness, which traps like every other member.
379
+ const have = new Set<string>()
380
+ for (let at: string | undefined = id; at; at = superId.get(at))
381
+ for (const member of children.get(at) ?? []) have.add(witnessKey(member))
382
+ const protocols: string[] = []
383
+ const visit = (protocolId: string) => {
384
+ if (protocols.includes(protocolId)) return
385
+ protocols.push(protocolId)
386
+ for (const edge of protocolParents.get(protocolId) ?? []) visit(edge)
387
+ }
388
+ for (const protocolId of conformIds.get(id) ?? []) visit(protocolId)
389
+ for (const protocolId of protocols)
390
+ for (const member of children.get(protocolId) ?? []) {
391
+ if (!requirement.has(member.identifier.precise) || optional.has(member.identifier.precise)) continue
392
+ if (isObjC(member) && / async\b/.test(text(member))) continue
393
+ if (have.has(witnessKey(member)) || member.kind.identifier === 'swift.associatedtype') continue
394
+ have.add(witnessKey(member))
395
+ emitWitness(member, inner, path)
396
+ }
397
+ const coder = members.some((member) => leaf(member) === 'init(coder:)')
398
+ if (designated && !coder && externalRoot(id) !== 'NSObject' && externalRoot(id) !== null)
399
+ emit(`${inner}public required init?(coder: NSCoder) { ${trap(`${path}.init(coder:)`)} }`)
400
+ emit(`${indent}}`)
401
+ return
402
+ }
403
+ case 'swift.struct': {
404
+ const shape = header(symbol, 'struct', indent)
405
+ if (!shape) return void skipped.push({ path, reason: `unparsed struct ${text(symbol)}` })
406
+ const members = membersOf(id)
407
+ const raw = rawType(members)
408
+ const list = inheritance(id)
409
+ emit(`${indent}${shape.attrs}public struct ${shape.name}${shape.generics}${list.length ? `: ${list.join(', ')}` : ''}${shape.where} {`)
410
+ if (raw) {
411
+ emit(`${inner}public let rawValue: ${raw}`)
412
+ emit(`${inner}public init(rawValue: ${raw}) { self.rawValue = rawValue }`)
413
+ }
414
+ for (const member of members) {
415
+ if (raw && (leaf(member) === 'rawValue' || leaf(member) === 'init(rawValue:)' || leaf(member) === 'init(_:)'))
416
+ continue
417
+ const value = values.get(member.identifier.precise)
418
+ if (value !== undefined && member.kind.identifier === 'swift.type.property') {
419
+ emit(`${inner}public static let ${tick(leaf(member))} = ${shape.name}(rawValue: ${value})`)
420
+ continue
421
+ }
422
+ emitMember(member, inner, { openOwner: false, inClass: false, ownerName: shape.name })
423
+ }
424
+ emit(`${indent}}`)
425
+ return
426
+ }
427
+ case 'swift.enum': {
428
+ const shape = header(symbol, 'enum', indent)
429
+ if (!shape) return void skipped.push({ path, reason: `unparsed enum ${text(symbol)}` })
430
+ const members = membersOf(id)
431
+ const raw = rawType(members)
432
+ const cases = (children.get(id) ?? []).filter((member) => member.kind.identifier === 'swift.enum.case')
433
+ const missing = raw ? cases.filter((member) => !values.has(member.identifier.precise)) : []
434
+ // an objective-c enum's numbering is the header's; without it the
435
+ // cases would invent values, so the enum is left out.
436
+ if (raw && isObjC(symbol) && missing.length > 0)
437
+ return void skipped.push({ path, reason: `no header value for ${missing.map(leaf).join(', ')}` })
438
+ const list = inheritance(id, raw ?? undefined).filter((name) => name !== 'RawRepresentable')
439
+ emit(`${indent}${shape.attrs}public enum ${shape.name}${shape.generics}${list.length ? `: ${list.join(', ')}` : ''}${shape.where} {`)
440
+ const seenValues = new Map<string, string>()
441
+ for (const member of cases) {
442
+ const value = values.get(member.identifier.precise)
443
+ // objective-c aliases a value under a second name; swift spells
444
+ // the alias as a static member of the first case.
445
+ if (value !== undefined && seenValues.has(value)) {
446
+ emit(`${inner}public static var ${tick(leaf(member))}: ${shape.name} { .${seenValues.get(value)} }`)
447
+ continue
448
+ }
449
+ if (value !== undefined) seenValues.set(value, tick(leaf(member)))
450
+ const caseText = text(member).replace(/^case\s+/, '')
451
+ emit(`${inner}case ${caseText}${value !== undefined ? ` = ${value}` : ''}`)
452
+ }
453
+ for (const member of members) {
454
+ if (member.kind.identifier === 'swift.enum.case') continue
455
+ if (raw && (leaf(member) === 'rawValue' || leaf(member) === 'init(rawValue:)')) continue
456
+ emitMember(member, inner, { openOwner: false, inClass: false, ownerName: shape.name })
457
+ }
458
+ emit(`${indent}}`)
459
+ return
460
+ }
461
+ case 'swift.protocol': {
462
+ const shape = header(symbol, 'protocol', indent)
463
+ if (!shape) return void skipped.push({ path, reason: `unparsed protocol ${text(symbol)}` })
464
+ // objective-c protocols are class-bound; swift needs it spelled.
465
+ const list = [...(isObjC(symbol) ? ['AnyObject'] : []), ...inheritance(id)]
466
+ emit(`${indent}${shape.attrs}public protocol ${shape.name}${list.length ? `: ${list.join(', ')}` : ''}${shape.where} {`)
467
+ const members = membersOf(id)
468
+ const defaults: GraphSymbol[] = []
469
+ for (const member of members) {
470
+ if (member.kind.identifier === 'swift.associatedtype') {
471
+ emit(`${inner}${text(member)}`)
472
+ continue
473
+ }
474
+ // objective-c imports a completion-handler requirement twice, the
475
+ // second as async; one witness satisfies both there, so the async
476
+ // spelling is an extension member here.
477
+ const asyncTwin = isObjC(member) && / async\b/.test(text(member))
478
+ if (!requirement.has(member.identifier.precise) || asyncTwin) {
479
+ defaults.push(member)
480
+ continue
481
+ }
482
+ emitRequirement(member, inner)
483
+ if (optional.has(member.identifier.precise)) defaults.push(member)
484
+ }
485
+ emit(`${indent}}`)
486
+ if (defaults.length > 0) {
487
+ emit(`${indent}extension ${path} {`)
488
+ for (const member of defaults) {
489
+ // an optional objective-c requirement the conformer leaves out
490
+ // is never called; a Void method's default is that no-op.
491
+ const decl = text(member)
492
+ if (optional.has(member.identifier.precise) && member.kind.identifier === 'swift.method' && !/->/.test(decl.replace(/\([^)]*\)/g, '')) && !/ async\b/.test(decl))
493
+ emitNoop(member, inner)
494
+ else emitMember(member, inner, { openOwner: false, inClass: false, ownerName: shape.name })
495
+ }
496
+ emit(`${indent}}`)
497
+ }
498
+ return
499
+ }
500
+ }
501
+ })
502
+
503
+ const emitWitness = (member: GraphSymbol, indent: string, owner: string) => {
504
+ const { 2: rest } = LEADING_ATTRS.exec(text(member))!
505
+ const decl = rest!.replace(/^(?:weak |unowned )/, '').replace(/^((?:static )?)let /, '$1var ')
506
+ const witness = `${owner}.${leaf(member)}`
507
+ const body = trap(witness)
508
+ if (member.kind.identifier === 'swift.property' || member.kind.identifier === 'swift.type.property') {
509
+ const accessors = ACCESSORS.exec(decl)
510
+ const bare = decl.replace(ACCESSORS, '').trimEnd()
511
+ emit(`${indent}public ${bare} { get { ${body} }${accessors?.[3] ? ` set { ${body} }` : ''} }`)
512
+ } else emit(`${indent}public ${member.kind.identifier === 'swift.init' ? 'required ' : ''}${stripDefaults(decl)} { ${body} }`)
513
+ }
514
+
515
+ const emitNoop = scoped((member: GraphSymbol, indent: string) => {
516
+ emit(`${indent}public ${stripDefaults(text(member))} {}`)
517
+ })
518
+
519
+ // a protocol requirement: no access modifier, body, or default values
520
+ const emitRequirement = scoped((member: GraphSymbol, indent: string) => {
521
+ const { 1: attrs, 2: rest } = LEADING_ATTRS.exec(text(member))!
522
+ emit(`${indent}${attrs}${stripDefaults(rest!.replace(/^(?:weak |unowned )/, '').replace(/^((?:static )?)let /, '$1var '))}`)
523
+ })
524
+
525
+ const rawType = (members: GraphSymbol[]) => {
526
+ const init = members.find((member) => leaf(member) === 'init(rawValue:)')
527
+ return init ? (/rawValue:\s*([^)]+)\)/.exec(text(init))?.[1]?.trim() ?? null) : null
528
+ }
529
+
530
+ const emitGlobal = scoped((symbol: GraphSymbol) => {
531
+ const path = pathOf(symbol)
532
+ if (symbol.kind.identifier === 'swift.func' || symbol.kind.identifier === 'swift.func.op') {
533
+ const { 1: attrs, 2: rest } = LEADING_ATTRS.exec(text(symbol))!
534
+ emit(`${attrs}public ${rest} { ${trap(path)} }`)
535
+ } else if (symbol.kind.identifier === 'swift.var') {
536
+ const decl = text(symbol).replace(/^let /, 'var ').replace(ACCESSORS, '').trimEnd()
537
+ emit(`public ${decl} { ${trap(path)} }`)
538
+ } else skipped.push({ path, reason: `unhandled top-level ${symbol.kind.identifier}` })
539
+ })
540
+
541
+ const roots = [...byId.values()]
542
+ .filter((symbol) => !owner.has(symbol.identifier.precise) && !unavailable(symbol))
543
+ .sort((a, b) => pathOf(a).localeCompare(pathOf(b)))
544
+ for (const symbol of roots) {
545
+ const path = pathOf(symbol)
546
+ if (TYPE_KINDS.has(symbol.kind.identifier)) emitType(symbol, '')
547
+ else emitGlobal(symbol)
548
+ }
549
+ for (const [name, members] of [...external].sort(([a], [b]) => a.localeCompare(b))) {
550
+ const seen = new Set<string>()
551
+ const kept = members.filter((member) => {
552
+ const key = `${member.kind.identifier}|${text(member)}`
553
+ if (unavailable(member) || seen.has(key)) return false
554
+ seen.add(key)
555
+ return true
556
+ })
557
+ if (kept.length === 0) continue
558
+ emit(`extension ${name} {`)
559
+ for (const member of kept)
560
+ if (member.kind.identifier === 'swift.init' && !text(member).startsWith('convenience'))
561
+ emitMember({ ...member, declarationFragments: [{ kind: 'text', spelling: `convenience ${text(member)}` }] }, ' ', {
562
+ openOwner: false,
563
+ inClass: true,
564
+ ownerName: name,
565
+ })
566
+ else emitMember(member, ' ', { openOwner: false, inClass: false, ownerName: name })
567
+ emit(`}`)
568
+ }
569
+
570
+ const imports = ['Foundation', 'UIKit', ...(options.imports ?? [])]
571
+ const banner = [
572
+ `// stand-in for the binary ${options.module} module, generated from ${options.source}.`,
573
+ `// do not hand-edit: every body traps because the vendor binary cannot run`,
574
+ `// in peach; behavior a hand file measures lives beside this file.`,
575
+ '',
576
+ ...imports.map((name) => `import ${name}`),
577
+ '',
578
+ ]
579
+ for (const path of behavior.keys())
580
+ if (!used.has(path)) skipped.push({ path, reason: 'behavior names no emitted declaration' })
581
+ return {
582
+ source: `${[...banner, ...lines].join('\n')}\n`,
583
+ skipped,
584
+ owners: [...banner.map(() => ''), ...owners],
585
+ }
586
+ }
587
+
588
+ const KEYWORDS = new Set(['Type', 'Protocol', 'Self', 'default', 'init', 'self', 'class', 'func', 'var', 'let', 'in', 'is', 'as', 'repeat', 'internal', 'public', 'private', 'operator', 'extension', 'subscript', 'static', 'struct', 'protocol', 'enum', 'case', 'where', 'return', 'throw', 'throws', 'import', 'true', 'false', 'nil'])
589
+ const tick = (name: string) => (KEYWORDS.has(name) ? `\`${name}\`` : name)
590
+
591
+ // requirements carry no default argument values
592
+ function stripDefaults(decl: string) {
593
+ let out = ''
594
+ let depth = 0
595
+ for (let at = 0; at < decl.length; at++) {
596
+ const char = decl[at]!
597
+ if (char === '(' || char === '[' || char === '<') depth++
598
+ if (char === ')' || char === ']' || (char === '>' && decl[at - 1] !== '-')) depth--
599
+ if (char === '=' && depth === 1 && decl[at - 1] === ' ') {
600
+ let skip = at + 1
601
+ let inner = 0
602
+ while (skip < decl.length) {
603
+ const next = decl[skip]!
604
+ if (next === '(' || next === '[') inner++
605
+ if (next === ')' || next === ']') {
606
+ if (inner === 0) break
607
+ inner--
608
+ }
609
+ if (next === ',' && inner === 0) break
610
+ skip++
611
+ }
612
+ out = out.trimEnd()
613
+ at = skip - 1
614
+ continue
615
+ }
616
+ out += char
617
+ }
618
+ return out
619
+ }