-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMergeDeclarations.swift
More file actions
333 lines (301 loc) · 12.8 KB
/
MergeDeclarations.swift
File metadata and controls
333 lines (301 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import WebIDL
enum DeclarationMerger {
static let ignoredTypedefs: Set<String> = [
"Function",
"AudioWorkletProcessorConstructor",
"CustomElementConstructor",
"ArrayBufferView",
"RotationMatrixType",
// Mapped to `Int32` manually. This can't be represented as `Int64` due to `BigInt` representation on JS side,
// but as a pointer it can't be represented as floating point number either.
"GLintptr",
]
static let ignoredIncludeTargets: Set<String> = ["WorkerNavigator"]
static let validExposures: Set<String> = ["Window"]
static let ignoredParents: Set<String> = ["LinkStyle"]
private static func enhanceMembers(_ members: [IDLNode]) -> [IDLNode] {
members.flatMap { member -> [IDLNode] in
if let named = member as? IDLNamed, named.name.contains("-") {
return []
}
if let operation = member as? IDLOperation,
case .generic("Promise", _) = operation.idlType?.value
{
return [member, AsyncOperation(operation: operation)]
} else {
return [member]
}
}.reduce(into: [IDLNode]()) { partialResult, node in
guard let operation = node as? IDLOperation else {
partialResult.append(node)
return
}
// annoyingly, the spec writers didn’t
switch operation.special {
case "getter":
if let setterIndex = partialResult.lastIndex(where: { node in
if let op = node as? IDLOperation {
return op.special == "setter" && op.arguments[1].idlType.value == operation.idlType?.value
} else {
return false
}
}) {
let setter = partialResult[setterIndex] as! IDLOperation
if setter.name.isEmpty {
partialResult.remove(at: setterIndex)
}
partialResult.append(SubscriptOperation(getter: operation, setter: setter))
} else {
partialResult.append(SubscriptOperation(getter: operation))
}
if !operation.name.isEmpty {
partialResult.append(operation)
}
case "setter":
if let subscriptIndex = partialResult.lastIndex(where: { node in
if let op = node as? SubscriptOperation {
return op.getter.idlType?.value == operation.arguments[1].idlType.value
} else {
return false
}
}) {
let subscriptOp = partialResult[subscriptIndex] as! SubscriptOperation
partialResult.remove(at: subscriptIndex)
partialResult.append(SubscriptOperation(getter: subscriptOp.getter, setter: operation))
} else {
partialResult.append(node)
}
default:
partialResult.append(node)
}
}
}
static func merge(declarations: [IDLNode]) -> MergeResult {
let byType: [String: [IDLNode]] = declarations.reduce(into: [:]) { partialResult, node in
partialResult[type(of: node).type, default: []].append(node)
}
let missedTypes = Set(declarations.map { type(of: $0).type })
.subtracting([
IDLInterfaceMixin.type,
IDLInterface.type,
IDLDictionary.type,
IDLCallbackInterface.type,
IDLIncludes.type,
IDLEnum.type, IDLNamespace.type,
IDLTypedef.type, IDLCallback.type,
])
if !missedTypes.isEmpty {
print("missed types!", missedTypes)
}
// let byName: [String?: [IDLNode]] = declarations.reduce(into: [:]) { partialResult, node in
// let name = Mirror(reflecting: node).children.first { $0.label == "name" }?.value as? String
// partialResult[name, default: []].append(node)
// }
// print(byName.filter { $0.value.count > 1 }.map { "\($0.key ?? "<nil>"): \($0.value.map { type(of: $0).type }))" }.joined(separator: "\n"))
func allNodes<T: IDLNode>(ofType _: T.Type) -> [T] {
byType[T.type]?.map { $0 as! T } ?? []
}
let mixins = Dictionary(
grouping: allNodes(ofType: IDLInterfaceMixin.self).map {
MergedMixin(
name: $0.name,
partial: $0.partial,
members: enhanceMembers($0.members.array) as! [IDLInterfaceMixinMember]
)
},
by: \.name
).mapValues {
$0.dropFirst().reduce(into: $0.first!) { partialResult, mixin in
partialResult.partial = partialResult.partial && mixin.partial
partialResult.members += mixin.members
}
}
var includes = Dictionary(grouping: allNodes(ofType: IDLIncludes.self)) { $0.target }
.mapValues { $0.map(\.includes).filter { !Self.ignoredParents.contains($0) } }
.filter { !$0.value.isEmpty }
.filter { !ignoredIncludeTargets.contains($0.key) }
let mergedInterfaces = Dictionary(
grouping: allNodes(ofType: IDLInterface.self).map {
MergedInterface(
name: $0.name,
partial: $0.partial,
parentClasses: [$0.inheritance]
.compactMap { $0 }
.filter { !Self.ignoredParents.contains($0) },
members: enhanceMembers($0.members.array) as! [IDLInterfaceMember],
exposed: Set(
$0.extAttrs
.filter { $0.name == "Exposed" }
.flatMap { $0.rhs?.identifiers ?? [] }
),
exposedToAll: $0.extAttrs.contains { $0.name == "Exposed" && $0.rhs == .wildcard },
global: $0.extAttrs.contains { $0.name == "Global" }
)
},
by: \.name
).mapValues { toMerge -> MergedInterface in
var interface = toMerge.dropFirst().reduce(into: toMerge.first!) { partialResult, interface in
partialResult.partial = partialResult.partial && interface.partial
partialResult.parentClasses += interface.parentClasses
partialResult.members += interface.members
partialResult.exposed.formUnion(interface.exposed)
partialResult.exposedToAll = partialResult.exposedToAll || interface.exposedToAll
partialResult.global = partialResult.global || interface.global
}
interface.mixins = includes.removeValue(forKey: interface.name) ?? []
if let decl = interface.members.first(where: { $0 is IDLIterableDeclaration }) as? IDLIterableDeclaration {
interface.mixins.append(decl.async ? "AsyncSequence" : "Sequence")
}
return interface
}.filter { $0.value.exposedToAll || $0.value.exposed.contains(where: validExposures.contains) }
let mergedDictionaries = Dictionary(
grouping: allNodes(ofType: IDLDictionary.self).map {
MergedDictionary(
name: $0.name,
inheritance: [$0.inheritance]
.compactMap { $0 }
.filter { !Self.ignoredParents.contains($0) },
members: $0.members
)
},
by: \.name
).mapValues { toMerge -> MergedDictionary in
var dict = toMerge.dropFirst().reduce(into: toMerge.first!) { partialResult, interface in
partialResult.inheritance += interface.inheritance
partialResult.members += interface.members
}
dict.inheritance += includes[dict.name, default: []]
return dict
}
let mergedNamespaces = Dictionary(
grouping: allNodes(ofType: IDLNamespace.self).map {
MergedNamespace(
name: $0.name,
members: enhanceMembers($0.members.array) as! [IDLNamespaceMember]
)
},
by: \.name
).mapValues {
$0.dropFirst().reduce(into: $0.first!) { partialResult, namespace in
partialResult.members += namespace.members
}
}
var allTypes: [IDLTypealias] = allNodes(ofType: IDLTypedef.self) + allNodes(ofType: IDLCallback.self)
allTypes.removeAll(where: { ignoredTypedefs.contains($0.name) })
let mergedTypes = Dictionary(uniqueKeysWithValues: allTypes.map { ($0.name, $0) })
// var unionAliases: [String: String] = [:]
// let unions = Set(
// Dictionary(
// all(IDLTypedef.self).compactMap { type -> (Set<SlimIDLType>, UnionType)? in
// if case let .union(types) = type.idlType.value {
// let typeSet = Set(types.map(SlimIDLType.init))
// return (typeSet, UnionType(types: typeSet, friendlyName: type.name))
// }
// return nil
// },
// uniquingKeysWith: { old, new in
// unionAliases[new.name] = old.name
// return old
// }
// ).values
// )
// print(unionAliases)
let arrays: [DeclarationFile] =
Array(mergedInterfaces.values)
+ Array(mergedDictionaries.values)
+ Array(mixins.values)
+ Array(mergedNamespaces.values)
+ Array(includes.map(Extension.init))
return MergeResult(
declarations: arrays
+ [Typedefs(typedefs: allTypes)]
+ allNodes(ofType: IDLEnum.self)
+ allNodes(ofType: IDLCallbackInterface.self),
dictionaries: mergedDictionaries,
interfaces: mergedInterfaces,
types: mergedTypes
// unions: unions
)
}
struct MergeResult {
let declarations: [DeclarationFile]
let dictionaries: [String: MergedDictionary]
let interfaces: [String: MergedInterface]
let types: [String: IDLTypealias]
// let unions: Set<UnionType>
}
}
protocol DeclarationFile {
var name: String { get }
}
extension IDLEnum: DeclarationFile {}
extension IDLCallbackInterface: DeclarationFile {}
struct AsyncOperation: IDLNode, IDLNamespaceMember, IDLInterfaceMember, IDLInterfaceMixinMember, IDLNamed {
static var type: String { "" }
var extAttrs: [IDLExtendedAttribute] { operation.extAttrs }
var name: String { operation.name }
let operation: IDLOperation
var returnType: IDLType {
guard case let .generic("Promise", values) = operation.idlType?.value else {
print(operation)
fatalError("Return type of async function \(name) is not a Promise")
}
return values.first!
}
}
struct SubscriptOperation: IDLNode, IDLInterfaceMember, IDLInterfaceMixinMember, IDLNamed {
static var type: String { "" }
var extAttrs: [IDLExtendedAttribute] {
precondition(getter.extAttrs.isEmpty)
precondition(setter?.extAttrs.isEmpty ?? true)
return []
}
var name: String { "subscript" }
let getter: IDLOperation
var setter: IDLOperation?
var returnType: IDLType {
getter.idlType!
}
}
struct MergedNamespace: DeclarationFile {
let name: String
var members: [IDLNamespaceMember]
}
struct MergedMixin: DeclarationFile {
let name: String
var partial: Bool
var members: [IDLInterfaceMixinMember]
}
struct MergedDictionary: DeclarationFile {
let name: String
var inheritance: [String]
var members: [IDLDictionary.Member]
}
struct MergedInterface: DeclarationFile {
let name: String
var partial: Bool
var parentClasses: [String]
var mixins: [String] = []
var members: [IDLInterfaceMember]
var exposed: Set<String>
var exposedToAll: Bool
var global: Bool
}
struct Extension: DeclarationFile {
// sort next to declaration of protocol, hopefully
var name: String { "\(protocols.joined(separator: ", ")) - \(conformer)" }
let conformer: String
var protocols: [String]
}
struct Typedefs: DeclarationFile, SwiftRepresentable {
let name = "Typedefs"
let typedefs: [IDLTypealias]
var swiftRepresentation: SwiftSource {
"\(lines: typedefs.filter { !DeclarationMerger.ignoredTypedefs.contains($0.name) }.map(toSwift))"
}
}
protocol IDLTypealias: IDLNode, IDLNamed {
var idlType: IDLType { get }
}
extension IDLCallback: IDLTypealias {}
extension IDLTypedef: IDLTypealias {}