From 43c8b573f5166bdd89c11edc5aeef7d9a0360447 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Fri, 14 Aug 2020 17:14:30 -0400 Subject: [PATCH 01/22] =?UTF-8?q?Mostly=20working,=20except=20for=20when?= =?UTF-8?q?=20it=20doesn=E2=80=99t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (enums containing objects and primitives) JavaScriptKit a87af4e --- Sources/Commands/GenerateCode.swift | 1 - .../IRGenerator.swift | 2 +- .../Member Nodes/ConstructorNode.swift | 10 +-- .../Member Nodes/MethodNode.swift | 12 ++-- .../Member Nodes/ReadWritePropertyNode.swift | 62 ++++++++++--------- .../Member Nodes/ReadonlyPropertyNode.swift | 4 +- .../Member Nodes/SubscriptNode.swift | 6 +- .../Type Nodes/BasicTypeNode.swift | 2 +- .../Type Nodes/ClassNode.swift | 8 +-- .../Type Nodes/DictionaryNode.swift | 16 ++--- .../EnumerationWithAssociatedValuesNode.swift | 25 ++++---- .../EnumerationWithRawValueNode.swift | 17 ++--- .../Type Nodes/NamespaceNode.swift | 2 +- .../TypeErasedWrapperStructNode.swift | 6 +- 14 files changed, 84 insertions(+), 89 deletions(-) diff --git a/Sources/Commands/GenerateCode.swift b/Sources/Commands/GenerateCode.swift index 0515ebb..c6613ac 100644 --- a/Sources/Commands/GenerateCode.swift +++ b/Sources/Commands/GenerateCode.swift @@ -85,7 +85,6 @@ public struct GenerateCode: ParsableCommand { */ import JavaScriptKit - import ECMAScript """ diff --git a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift index be8087e..d92e4e3 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift @@ -183,7 +183,7 @@ public class IRGenerator { return handleReadOnlyMember(readOnlyMember) case .stringifier: - // Not required: JSBridgedType conforms to CustomStringConvertible + // Not required: JSBridgedClass conforms to CustomStringConvertible return nil case .staticMember(let staticMember, _): diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift index f10130a..35bd5ce 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift @@ -107,23 +107,23 @@ class ConstructorNode: MemberNode, Equatable { let returnValue: String if closureNode.returnType.identifier == "Void" { - returnValue = "; return .undefined" + returnValue = "" } else { - returnValue = ".fromJSValue()" + returnValue = ".fromJSValue()!" } let argumentCount = closureNode.arguments.count let closureArguments = (0 ..< argumentCount) - .map { "$0[\($0)].fromJSValue()" } + .map { "$0[\($0)].fromJSValue()!" } .joined(separator: ", ") - return "JSFunctionRef.from({ \($0.label)(\(closureArguments))\(returnValue) })" + return "JSClosure { \($0.label)(\(closureArguments))\(returnValue) }" } else { return $0.label + ".jsValue()" } } declaration += """ { - self.init(objectRef: \(className).classRef.new(\(passedParameters.joined(separator: ", ")))) + self.init(withCompatibleObject: \(className).classRef.new(\(passedParameters.joined(separator: ", ")))) } """ } diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift index b96cd13..deea394 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift @@ -116,16 +116,16 @@ class MethodNode: MemberNode, Equatable { let returnValue: String if closureNode.returnType.identifier == "Void" { - returnValue = "; return .undefined" + returnValue = "" } else { - returnValue = ".fromJSValue()" + returnValue = ".fromJSValue()!" } let argumentCount = closureNode.arguments.count let closureArguments = (0 ..< argumentCount) - .map { "$0[\($0)].fromJSValue()" } + .map { "$0[\($0)].fromJSValue()!" } .joined(separator: ", ") - return "JSFunctionRef.from({ \($0.label)(\(closureArguments))\(returnValue) })" + return "JSClosure { \($0.label)(\(closureArguments))\(returnValue) }" } else { return $0.label + ".jsValue()" } @@ -140,13 +140,13 @@ class MethodNode: MemberNode, Equatable { } else if unwrapNode(returnType).isProtocol { declaration += """ { - return objectRef.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue() as \(unwrapNode(returnType).typeErasedSwiftType) + return objectRef.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue()! as \(unwrapNode(returnType).typeErasedSwiftType) } """ } else { declaration += """ { - return objectRef.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue() + return objectRef.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue()! } """ } diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift index c9ab1f5..dbf58fd 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift @@ -49,58 +49,59 @@ class ReadWritePropertyNode: PropertyNode, Equatable { let declaration: String let dataTypeNode = unwrapNode(dataType) + let escaped = escapedName(name) switch (inContext, isStatic) { case (.classContext, false) where dataTypeNode.isProtocol: - return "public var \(escapedName(name)): \(dataTypeNode.swiftTypeName)" + return "public var \(escaped): \(dataTypeNode.swiftTypeName)" case (.classContext, true) where dataTypeNode.isProtocol: - return "public static var \(escapedName(name)): \(dataTypeNode.swiftTypeName)" + return "public static var \(escaped): \(dataTypeNode.swiftTypeName)" case (.classContext, false) where dataTypeNode.isClosure && dataTypeNode.isOptional && dataTypeNode.numberOfClosureArguments == 1: declaration = """ @OptionalClosureHandler - public var \(escapedName(name)): \(dataTypeNode.swiftTypeName) + public var \(escaped): \(dataTypeNode.swiftTypeName) """ case (.classContext, true) where dataTypeNode.isClosure && dataTypeNode.isOptional && dataTypeNode.numberOfClosureArguments == 1: declaration = """ @OptionalClosureHandler(objectRef: Self.classRef, name: "\(name)") - public static var \(escapedName(name)): \(dataTypeNode.swiftTypeName) + public static var \(escaped): \(dataTypeNode.swiftTypeName) """ case (.classContext, false) where dataTypeNode.isClosure && dataTypeNode.numberOfClosureArguments == 1: declaration = """ @ClosureHandler - public var \(escapedName(name)): \(dataTypeNode.swiftTypeName) + public var \(escaped): \(dataTypeNode.swiftTypeName) """ case (.classContext, true) where dataTypeNode.isClosure && dataTypeNode.numberOfClosureArguments == 1: declaration = """ @ClosureHandler(objectRef: Self.classRef, name: "\(name)") - public var \(escapedName(name)): \(dataTypeNode.swiftTypeName) + public var \(escaped): \(dataTypeNode.swiftTypeName) """ case (.classContext, false) where isOverride: declaration = """ - public override var \(escapedName(name)): \(dataTypeNode.swiftTypeName) { + public override var \(escaped): \(dataTypeNode.swiftTypeName) { get { - return objectRef[dynamicMember: "\(name)"] + return objectRef.\(escaped) } set { - objectRef[dynamicMember: "\(name)"] = newValue + objectRef.\(escaped) = newValue } } """ case (.classContext, true) where isOverride: declaration = """ - public static override var \(escapedName(name)): \(dataTypeNode.swiftTypeName) { + public static override var \(escaped): \(dataTypeNode.swiftTypeName) { get { - return objectRef[dynamicMember: "\(name)"] + return objectRef.\(escaped) } set { - objectRef[dynamicMember: "\(name)"] = newValue + objectRef\(escaped) = newValue } } """ @@ -108,17 +109,17 @@ class ReadWritePropertyNode: PropertyNode, Equatable { case (.classContext, false): declaration = """ @ReadWriteAttribute - public var \(escapedName(name)): \(dataTypeNode.swiftTypeName) + public var \(escaped): \(dataTypeNode.swiftTypeName) """ case (.classContext, true): declaration = """ @ReadWriteAttribute(objectRef: Self.classRef, name: "\(name)") - public static var \(escapedName(name)): \(dataTypeNode.swiftTypeName) + public static var \(escaped): \(dataTypeNode.swiftTypeName) """ case (.protocolContext, _), (.extensionContext, _), (.structContext, _): - declaration = "var \(escapedName(name)): \(dataTypeNode.swiftTypeName)" + declaration = "var \(escaped): \(dataTypeNode.swiftTypeName)" case (.namespaceContext, _): fatalError("Not supported by Web IDL standard!") @@ -137,6 +138,7 @@ class ReadWritePropertyNode: PropertyNode, Equatable { func swiftImplementations(inContext: MemberNodeContext) -> [String] { let dataTypeNode = unwrapNode(dataType) + let escaped = escapedName(name) switch inContext { case .classContext where dataTypeNode.isProtocol, .protocolContext where dataTypeNode.isProtocol, @@ -146,10 +148,10 @@ class ReadWritePropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(name).fromJSValue() as \(dataTypeNode.typeErasedSwiftType) + return objectRef.\(escaped).fromJSValue()! as \(dataTypeNode.typeErasedSwiftType) } set { - objectRef.\(name) = newValue.jsValue() + objectRef.\(escaped) = newValue.jsValue()! } } """ @@ -163,23 +165,23 @@ class ReadWritePropertyNode: PropertyNode, Equatable { .structContext where dataTypeNode.isOptional && dataTypeNode.isClosure, .classContext where dataTypeNode.isOptional && dataTypeNode.isClosure: let getterArguments = (0 ..< dataTypeNode.numberOfClosureArguments).map({ "arg\($0)" }).joined(separator: ", ") - let setterArguments = (0 ..< dataTypeNode.numberOfClosureArguments).map({ "arguments[\($0)].fromJSValue()" }).joined(separator: ", ") + let setterArguments = (0 ..< dataTypeNode.numberOfClosureArguments).map({ "arguments[\($0)].fromJSValue()!" }).joined(separator: ", ") return [ _swiftDeclarations(inContext: inContext) + """ { get { - guard let function = objectRef[dynamicMember: "\(name)"] as JSFunctionRef? else { + guard let function = objectRef.\(escaped).function else { return nil } - return { (\(getterArguments)) in function.dynamicallyCall(withArguments: [\(getterArguments)]).fromJSValue() } + return { (\(getterArguments)) in function(\(getterArguments)).fromJSValue()! } } set { if let newValue = newValue { - objectRef[dynamicMember: "\(name)"] = JSFunctionRef.from({ arguments in + objectRef.\(escaped) = JSClosure { arguments in return newValue(\(setterArguments)).jsValue() - }).jsValue() + }.jsValue() } else { - objectRef[dynamicMember: "\(name)"] = .null + objectRef.\(escaped) = .null } } } @@ -191,18 +193,18 @@ class ReadWritePropertyNode: PropertyNode, Equatable { .structContext where dataTypeNode.isClosure, .classContext: let getterArguments = (0 ..< dataTypeNode.numberOfClosureArguments).map({ "arg\($0)" }).joined(separator: ", ") - let setterArguments = (0 ..< dataTypeNode.numberOfClosureArguments).map({ "arguments[\($0)].fromJSValue()" }).joined(separator: ", ") + let setterArguments = (0 ..< dataTypeNode.numberOfClosureArguments).map({ "arguments[\($0)].fromJSValue()!" }).joined(separator: ", ") return [ _swiftDeclarations(inContext: inContext) + """ { get { - let function = objectRef[dynamicMember: "\(name)"] as JSFunctionRef - return { (\(getterArguments)) in function.dynamicallyCall(withArguments: [\(getterArguments)]).fromJSValue() } + let function = objectRef.\(escaped).function! + return { (\(getterArguments)) in function(\(getterArguments)).fromJSValue()! } } set { - objectRef[dynamicMember: "\(name)"] = JSFunctionRef.from({ arguments in + objectRef.\(escaped) = JSClosure { arguments in return newValue(\(setterArguments)).jsValue() - }).jsValue() + }.jsValue() } } """ @@ -215,10 +217,10 @@ class ReadWritePropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(name).fromJSValue() + return objectRef.\(escaped).fromJSValue()! } set { - objectRef.\(name) = newValue.jsValue() + objectRef.\(escaped) = newValue.jsValue() } } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift index 8ea115d..1508c4b 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift @@ -81,7 +81,7 @@ class ReadonlyPropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(name).fromJSValue() as \(dataTypeNode.typeErasedSwiftType) + return objectRef.\(name).fromJSValue()! as \(dataTypeNode.typeErasedSwiftType) } } """ @@ -95,7 +95,7 @@ class ReadonlyPropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(name).fromJSValue() + return objectRef.\(name).fromJSValue()! } } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift index ae91871..abbdd31 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift @@ -70,7 +70,7 @@ class SubscriptNode: MemberNode, Equatable { let lookup: String declaration += " {\n" if isNamed { - lookup = "objectRef[dynamicMember: \(nameParameter.label)]" + lookup = "objectRef.\(escapedName(nameParameter.label))" } else { lookup = "objectRef[\(nameParameter.label)]" } @@ -78,13 +78,13 @@ class SubscriptNode: MemberNode, Equatable { if returnTypeNode.isProtocol { declaration += """ get { - return \(lookup).fromJSValue() as \(returnTypeNode.typeErasedSwiftType) + return \(lookup).fromJSValue()! as \(returnTypeNode.typeErasedSwiftType) } """ } else { declaration += """ get { - return \(lookup).fromJSValue() + return \(lookup).fromJSValue()! } """ } diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/BasicTypeNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/BasicTypeNode.swift index bb8f9c3..b28e3aa 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/BasicTypeNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/BasicTypeNode.swift @@ -44,7 +44,7 @@ class BasicArrayTypeNode: TypeNode, Equatable { } var swiftTypeName: String { - typeName + "JSTypedArray<\(scalarType)>" } var arrayElementSwiftTypeName: String? { diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift index 6283388..2ba2a8a 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift @@ -60,7 +60,7 @@ class ClassNode: TypeNode, Equatable { inheritance = (sorted.map { unwrapNode($0).swiftTypeName } + adoptedProtocols).joined(separator: ", ") } else { isBaseClass = true - inheritance = (["JSBridgedType"] + sorted.map { unwrapNode($0).swiftTypeName } + adoptedProtocols).joined(separator: ", ") + inheritance = (["JSBridgedClass"] + sorted.map { unwrapNode($0).swiftTypeName } + adoptedProtocols).joined(separator: ", ") } if isBaseClass { @@ -71,7 +71,7 @@ class ClassNode: TypeNode, Equatable { public let objectRef: JSObjectRef - public required init(objectRef: JSObjectRef) { + public required init(withCompatibleObject objectRef: JSObjectRef) { \(propertyNodes.compactMap { $0.initializationStatement(forContext: context) }.joined(separator: "\n")) self.objectRef = objectRef } @@ -83,9 +83,9 @@ class ClassNode: TypeNode, Equatable { public override class var classRef: JSFunctionRef { JSObjectRef.global.\(typeName).function! } - public required init(objectRef: JSObjectRef) { + public required init(withCompatibleObject objectRef: JSObjectRef) { \(propertyNodes.compactMap { $0.initializationStatement(forContext: context) }.joined(separator: "\n")) - super.init(objectRef: objectRef) + super.init(withCompatibleObject: objectRef) } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift index 6142dd8..dfe1169 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift @@ -61,11 +61,7 @@ class DictionaryNode: TypeNode, Equatable { let cases = self.cases return """ - public struct \(swiftTypeName): ExpressibleByDictionaryLiteral, JSValueCodable { - - public static func canDecode(from jsValue: JSValue) -> Bool { - return jsValue.isObject - } + public struct \(swiftTypeName): ExpressibleByDictionaryLiteral, JSBridgedType { public enum Key: String, Hashable { @@ -88,11 +84,15 @@ class DictionaryNode: TypeNode, Equatable { dictionary[key.rawValue] } - public init(jsValue: JSValue) { - - self.dictionary = jsValue.fromJSValue() + public init?(objectRef: JSObjectRef) { + if let dictionary: [String : AnyJSValueCodable] = objectRef.jsValue().fromJSValue() { + self.dictionary = dictionary + } + return nil } + public var objectRef: JSObjectRef { jsValue().object! } + public func jsValue() -> JSValue { return dictionary.jsValue() } diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift index 6cb9a33..5d16552 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift @@ -95,17 +95,9 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { } } - let inheritance = ["JSValueEncodable", "JSValueDecodable"] + protocolConfromances.sorted() + let inheritance = ["JSBridgedType"] + protocolConfromances.sorted() - var declaration = """ - public enum \(typeName): \(inheritance.joined(separator: ", ")) { - - public static func canDecode(from jsValue: JSValue) -> Bool { - return \(cases.map { "\(unwrapNode($0).swiftTypeName).canDecode(from: jsValue)" }.joined(separator: " || ")) - } - - - """ + var declaration = "public enum \(typeName): \(inheritance.joined(separator: ", ")) {\n" var initMap = [String]() declaration += zip(caseNames, cases) @@ -114,8 +106,8 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { let typeName = unwrapNode(nodePointer).swiftTypeName initMap.append(""" - if \(typeName).canDecode(from: jsValue) { - self = .\(caseName)(jsValue.fromJSValue()) + if let value = \(typeName)(objectRef: objectRef) { + self = .\(caseName)(value) } """) @@ -132,7 +124,7 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { declaration += """ - public init(jsValue: JSValue) { + public init?(objectRef: JSObjectRef) { """ declaration += initMap.joined(separator: " else ") @@ -143,8 +135,13 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { declaration += "\n\n" declaration += """ - public func jsValue() -> JSValue { + public var objectRef: JSObjectRef { + switch self { + \(caseNames.map { "case .\($0)(let v): return v.objectRef" }.joined(separator: "\n")) + } + } + public func jsValue() -> JSValue { switch self { \(caseNames.map { "case .\($0)(let v): return v.jsValue()" }.joined(separator: "\n")) } diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithRawValueNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithRawValueNode.swift index 12efb6a..a26f064 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithRawValueNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithRawValueNode.swift @@ -37,8 +37,12 @@ class EnumerationWithRawValueNode: TypeNode, Equatable { var declaration = """ public enum \(typeName): String, JSValueCodable { - public static func canDecode(from jsValue: JSValue) -> Bool { - return jsValue.isString + public static func construct(from jsValue: JSValue) -> \(typeName)? { + if let string = jsValue.string, + let value = \(typeName)(rawValue: string) { + return value + } + return nil } """ @@ -46,15 +50,6 @@ class EnumerationWithRawValueNode: TypeNode, Equatable { declaration += casesAndRawValues.map { "case \($0.0) = \"\($0.1)\"" }.joined(separator: "\n") declaration += """ - - public init(jsValue: JSValue) { - - guard let value = \(typeName)(rawValue: jsValue.fromJSValue()) else { - fatalError() - } - self = value - } - public func jsValue() -> JSValue { return rawValue.jsValue() } diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift index 7257093..5e51575 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift @@ -33,7 +33,7 @@ class NamespaceNode: TypeNode, Equatable { public static var objectRef: JSObjectRef { return JSObjectRef.global.\(typeName).object! - } + }\n """ declaration += members diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift index db5aea4..12b09f0 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift @@ -28,11 +28,13 @@ class TypeErasedWrapperStructNode: TypeNode, Equatable { // swiftlint:enable force_cast var declaration = """ - class \(swiftTypeName): JSBridgedType, \(unwrapNode(wrapped).swiftTypeName) { + class \(swiftTypeName): JSBridgedClass, \(unwrapNode(wrapped).swiftTypeName) { + + public class var classRef: JSFunctionRef { JSObjectRef.global.\(wrapped.identifier).function! } let objectRef: JSObjectRef - required init(objectRef: JSObjectRef) { + required init(withCompatibleObject objectRef: JSObjectRef) { self.objectRef = objectRef } From 05be8d7544ecbdf64bd8dd819998e6d3925ae5a6 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Fri, 14 Aug 2020 17:31:50 -0400 Subject: [PATCH 02/22] More changes to get it finished! --- .../Type Nodes/DictionaryNode.swift | 6 +++--- .../EnumerationWithAssociatedValuesNode.swift | 12 ++++-------- .../Type Nodes/ProtocolNode.swift | 2 +- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift index dfe1169..b6f53d8 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift @@ -84,14 +84,14 @@ class DictionaryNode: TypeNode, Equatable { dictionary[key.rawValue] } - public init?(objectRef: JSObjectRef) { - if let dictionary: [String : AnyJSValueCodable] = objectRef.jsValue().fromJSValue() { + public init?(from value: JSValue) { + if let dictionary: [String : AnyJSValueCodable] = value.fromJSValue() { self.dictionary = dictionary } return nil } - public var objectRef: JSObjectRef { jsValue().object! } + public var value: JSValue { jsValue() } public func jsValue() -> JSValue { return dictionary.jsValue() diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift index 5d16552..b71e497 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift @@ -106,8 +106,8 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { let typeName = unwrapNode(nodePointer).swiftTypeName initMap.append(""" - if let value = \(typeName)(objectRef: objectRef) { - self = .\(caseName)(value) + if let decoded: \(typeName) = value.fromJSValue() { + self = .\(caseName)(decoded) } """) @@ -124,7 +124,7 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { declaration += """ - public init?(objectRef: JSObjectRef) { + public init?(from value: JSValue) { """ declaration += initMap.joined(separator: " else ") @@ -135,11 +135,7 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { declaration += "\n\n" declaration += """ - public var objectRef: JSObjectRef { - switch self { - \(caseNames.map { "case .\($0)(let v): return v.objectRef" }.joined(separator: "\n")) - } - } + public var value: JSValue { jsValue() } public func jsValue() -> JSValue { switch self { diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift index 66d8b25..f525f8d 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift @@ -40,7 +40,7 @@ class ProtocolNode: TypeNode, Equatable { let (namedSubscript, indexedSubscript) = SubscriptNode.mergedSubscriptNodes(requiredMembers.filter { $0.isSubscript } as! [SubscriptNode]) // swiftlint:enable force_cast - let inheritsFrom = ["JSBridgedType"] + self.inheritsFrom.map { unwrapNode($0).swiftTypeName }.sorted() + let inheritsFrom = ["JSBridgedClass"] + self.inheritsFrom.map { unwrapNode($0).swiftTypeName }.sorted() var declaration = """ public protocol \(typeName): \(inheritsFrom.joined(separator: ", ")) { From dd7d2b60f7dd78414b1c11302fb846c6704654db Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Fri, 14 Aug 2020 20:05:53 -0400 Subject: [PATCH 03/22] Correctly set the ancestor for callback interfaces --- .../IntermediateRepresentation/IRGenerator.swift | 4 ++-- .../IntermediateRepresentation.swift | 11 +++++++++-- .../Type Nodes/ProtocolNode.swift | 14 ++++++++++++-- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift index d92e4e3..83b3045 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift @@ -137,7 +137,7 @@ public class IRGenerator { } } - ir.registerProtocol(withTypeName: mixin.identifier, inheritsFrom: [], requiredMembers: [], defaultImplementations: members) + ir.registerProtocol(withTypeName: mixin.identifier, inheritsFrom: [], requiredMembers: [], defaultImplementations: members, kind: .mixin) } func handleEnum(_ enumeration: Enum) { @@ -222,7 +222,7 @@ public class IRGenerator { } } - ir.registerProtocol(withTypeName: callbackInterface.identifer, inheritsFrom: [], requiredMembers: requiredMembers, defaultImplementations: defaultImplementations) + ir.registerProtocol(withTypeName: callbackInterface.identifer, inheritsFrom: [], requiredMembers: requiredMembers, defaultImplementations: defaultImplementations, kind: .callback) } func handleTypedef(_ typedef: Typedef) { diff --git a/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift index 6bb4ccd..9ad9572 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift @@ -57,6 +57,13 @@ public class NodePointer: Hashable { } } +public enum ProtocolKind { + /// `callback interface` + case callback + /// `interface mixin` + case mixin +} + public class IntermediateRepresentation: Collection { public typealias Index = Swift.Dictionary.Index @@ -240,7 +247,7 @@ public class IntermediateRepresentation: Collection { } @discardableResult - func registerProtocol(withTypeName typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode]) -> NodePointer { + func registerProtocol(withTypeName typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode], kind: ProtocolKind) -> NodePointer { let nodePointer = existingOrNewNodePointer(for: typeName) let typeErasedPointer = existingOrNewNodePointer(for: "Any\(typeName)") @@ -252,7 +259,7 @@ public class IntermediateRepresentation: Collection { existingProtocolNode.requiredMembers.append(contentsOf: requiredMembers) existingProtocolNode.defaultImplementations.append(contentsOf: defaultImplementations) } else { - nodePointer.node = ProtocolNode(typeName: typeName, inheritsFrom: inheritsFrom, requiredMembers: requiredMembers, defaultImplementations: defaultImplementations) + nodePointer.node = ProtocolNode(typeName: typeName, inheritsFrom: inheritsFrom, requiredMembers: requiredMembers, defaultImplementations: defaultImplementations, kind: kind) typeErasedPointer.node = TypeErasedWrapperStructNode(wrapped: nodePointer) } diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift index f525f8d..51ec66a 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift @@ -8,15 +8,17 @@ class ProtocolNode: TypeNode, Equatable { let typeName: String var inheritsFrom: Set + let kind: ProtocolKind var requiredMembers: [MemberNode] var defaultImplementations: [MemberNode] - internal init(typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode]) { + internal init(typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode], kind: ProtocolKind) { self.typeName = typeName self.inheritsFrom = inheritsFrom self.requiredMembers = requiredMembers self.defaultImplementations = defaultImplementations + self.kind = kind } var isProtocol: Bool { @@ -40,7 +42,15 @@ class ProtocolNode: TypeNode, Equatable { let (namedSubscript, indexedSubscript) = SubscriptNode.mergedSubscriptNodes(requiredMembers.filter { $0.isSubscript } as! [SubscriptNode]) // swiftlint:enable force_cast - let inheritsFrom = ["JSBridgedClass"] + self.inheritsFrom.map { unwrapNode($0).swiftTypeName }.sorted() + let primaryType: String + switch kind { + case .callback: + primaryType = "JSBridgedType" + case .mixin: + primaryType = "JSBridgedClass" + } + + let inheritsFrom = [primaryType] + self.inheritsFrom.map { unwrapNode($0).swiftTypeName }.sorted() var declaration = """ public protocol \(typeName): \(inheritsFrom.joined(separator: ", ")) { From 0ec32037d2e4f3ef21d1544c136f56b6fb502c20 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Fri, 14 Aug 2020 22:40:50 -0400 Subject: [PATCH 04/22] It works! --- .../Member Nodes/MethodNode.swift | 88 +++++++++++++++---- 1 file changed, 72 insertions(+), 16 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift index deea394..3653b07 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift @@ -20,16 +20,61 @@ class MethodNode: MemberNode, Equatable { true } - // swiftlint:disable cyclomatic_complexity function_body_length - private func _swiftDeclaration(inContext context: MemberNodeContext, withImplementation: Bool) -> [String] { - - var declarations = [String]() + private func _generateOverloads() -> [[ParameterNode]] { var parameters = self.parameters - var removedParameter = false + var overloads = [parameters] repeat { removedParameter = false + if let index = parameters.lastIndex(where: { $0.isOmittable && $0.defaultValue == nil }) { + parameters.removeSubrange( index ..< parameters.endIndex) + overloads.append(parameters) + removedParameter = true + } + } while removedParameter || parameters.contains(where: { $0.isOmittable && $0.defaultValue == nil }) + + for parameter in parameters { + let isOptional = parameter.dataType.node!.isOptional + guard let node = (isOptional ? (parameter.dataType.node as? OptionalNode)?.wrapped.node : parameter.dataType.node) as? ProtocolNode, + node.kind == .callback + else { continue } + for params in overloads { + var params = params + guard let idx = params.firstIndex(where: { $0.label == parameter.label }) else { continue } + let param = params[idx] + let method = node.requiredMembers.first { $0.isMethod && !$0.isStatic && !$0.isSubscript } as! MethodNode + let closureNode = ClosureNode(arguments: method.parameters.map { $0.dataType }, returnType: method.returnType) + params[idx] = ParameterNode( + label: param.label, + dataType: NodePointer( + identifier: param.dataType.identifier, + node: isOptional + ? OptionalNode( + wrapped: NodePointer( + identifier: (param.dataType.node as! OptionalNode).wrapped.identifier, + node: closureNode + ) + ) + : closureNode + ), + isVariadic: param.isVariadic, + isOmittable: param.isOmittable, + defaultValue: param.defaultValue + ) + overloads.append(params) + } + } + + return overloads + } + + // swiftlint:disable cyclomatic_complexity function_body_length + private func _swiftDeclaration(inContext context: MemberNodeContext, withImplementation: Bool) -> [String] { + var declarations = [String]() + let overloads = _generateOverloads() + + for parameters in overloads { var declaration: String switch context { @@ -59,7 +104,11 @@ class MethodNode: MemberNode, Equatable { typeConstraints.append("\(type): \(dataTypeNode.swiftTypeName)") } } else if dataTypeNode.isClosure { - type = "@escaping \(dataTypeNode.swiftTypeName)" + if dataTypeNode.isOptional { + type = dataTypeNode.swiftTypeName + } else { + type = "@escaping \(dataTypeNode.swiftTypeName)" + } } else { type = dataTypeNode.swiftTypeName } @@ -103,29 +152,41 @@ class MethodNode: MemberNode, Equatable { let dataTypeNode = unwrapNode($0.dataType) if dataTypeNode.isClosure { + let closureOptional: Bool let closureNode: ClosureNode if let cNode = dataTypeNode as? ClosureNode { - closureNode = cNode + closureNode = cNode + closureOptional = false } else if let aliasNode = dataTypeNode as? AliasNode, let cNode = aliasNode.aliased as? ClosureNode { closureNode = cNode + closureOptional = false } else if let aliasNode = dataTypeNode as? AliasNode, let optionalNode = aliasNode.aliased as? OptionalNode, let cNode = optionalNode.wrapped.node as? ClosureNode { closureNode = cNode + closureOptional = false // FIXME: or true? + } else if let optionalNode = dataTypeNode as? OptionalNode, let cNode = optionalNode.wrapped.node as? ClosureNode { + closureNode = cNode + closureOptional = true } else { - fatalError("Unknown closure type.") + fatalError("Unknown closure type \(dataTypeNode).") } let returnValue: String if closureNode.returnType.identifier == "Void" { returnValue = "" } else { - returnValue = ".fromJSValue()!" + returnValue = ".jsValue()" } let argumentCount = closureNode.arguments.count let closureArguments = (0 ..< argumentCount) .map { "$0[\($0)].fromJSValue()!" } .joined(separator: ", ") - return "JSClosure { \($0.label)(\(closureArguments))\(returnValue) }" + let closureCode = "JSClosure { \($0.label)\(closureOptional ? "!" : "")(\(closureArguments))\(returnValue) }" + if closureOptional { + return "\($0.label) == nil ? nil : \(closureCode)" + } else { + return closureCode + } } else { return $0.label + ".jsValue()" } @@ -153,12 +214,7 @@ class MethodNode: MemberNode, Equatable { } declarations.append(declaration) - - if let index = parameters.lastIndex(where: { $0.isOmittable && $0.defaultValue == nil }) { - parameters.removeSubrange( index ..< parameters.endIndex) - removedParameter = true - } - } while removedParameter || parameters.contains(where: { $0.isOmittable && $0.defaultValue == nil }) + } return declarations } From f6cfe1a44877573d0f13eab11a5e1eca887f22dc Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Tue, 15 Sep 2020 10:42:12 -0400 Subject: [PATCH 05/22] Updates to match latest JSKit --- .../Member Nodes/ConstructorNode.swift | 2 +- .../Member Nodes/MethodNode.swift | 6 ++-- .../Member Nodes/ReadWritePropertyNode.swift | 36 +++++++++---------- .../Member Nodes/ReadonlyPropertyNode.swift | 8 ++--- .../Member Nodes/SubscriptNode.swift | 4 +-- .../Type Nodes/ClassNode.swift | 14 ++++---- .../Type Nodes/NamespaceNode.swift | 4 +-- .../TypeErasedWrapperStructNode.swift | 8 ++--- 8 files changed, 41 insertions(+), 41 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift index 35bd5ce..98f5b7c 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift @@ -123,7 +123,7 @@ class ConstructorNode: MemberNode, Equatable { } declaration += """ { - self.init(withCompatibleObject: \(className).classRef.new(\(passedParameters.joined(separator: ", ")))) + self.init(withCompatibleObject: \(className).constructor.new(\(passedParameters.joined(separator: ", ")))) } """ } diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift index 3653b07..4511035 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift @@ -195,19 +195,19 @@ class MethodNode: MemberNode, Equatable { if returnType.identifier == "Void" { declaration += """ { - _ = objectRef.\(name)!(\(passedParameters.joined(separator: ", "))) + _ = jsObject.\(name)!(\(passedParameters.joined(separator: ", "))) } """ } else if unwrapNode(returnType).isProtocol { declaration += """ { - return objectRef.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue()! as \(unwrapNode(returnType).typeErasedSwiftType) + return jsObject.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue()! as \(unwrapNode(returnType).typeErasedSwiftType) } """ } else { declaration += """ { - return objectRef.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue()! + return jsObject.\(name)!(\(passedParameters.joined(separator: ", "))).fromJSValue()! } """ } diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift index dbf58fd..cbf26c5 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift @@ -32,11 +32,11 @@ class ReadWritePropertyNode: PropertyNode, Equatable { if dataTypeNode.isClosure && dataTypeNode.numberOfClosureArguments == 1 { return """ - _\(name) = \(dataTypeNode.isOptional ? "OptionalClosureHandler" : "ClosureHandler")(objectRef: objectRef, name: "\(name)") + _\(name) = \(dataTypeNode.isOptional ? "OptionalClosureHandler" : "ClosureHandler")(jsObject: jsObject, name: "\(name)") """ } else if !isOverride { return """ - _\(name) = ReadWriteAttribute(objectRef: objectRef, name: "\(name)") + _\(name) = ReadWriteAttribute(jsObject: jsObject, name: "\(name)") """ } else { return nil @@ -66,7 +66,7 @@ class ReadWritePropertyNode: PropertyNode, Equatable { case (.classContext, true) where dataTypeNode.isClosure && dataTypeNode.isOptional && dataTypeNode.numberOfClosureArguments == 1: declaration = """ - @OptionalClosureHandler(objectRef: Self.classRef, name: "\(name)") + @OptionalClosureHandler(jsObject: Self.constructor, name: "\(name)") public static var \(escaped): \(dataTypeNode.swiftTypeName) """ @@ -78,7 +78,7 @@ class ReadWritePropertyNode: PropertyNode, Equatable { case (.classContext, true) where dataTypeNode.isClosure && dataTypeNode.numberOfClosureArguments == 1: declaration = """ - @ClosureHandler(objectRef: Self.classRef, name: "\(name)") + @ClosureHandler(jsObject: Self.constructor, name: "\(name)") public var \(escaped): \(dataTypeNode.swiftTypeName) """ @@ -86,10 +86,10 @@ class ReadWritePropertyNode: PropertyNode, Equatable { declaration = """ public override var \(escaped): \(dataTypeNode.swiftTypeName) { get { - return objectRef.\(escaped) + return jsObject.\(escaped) } set { - objectRef.\(escaped) = newValue + jsObject.\(escaped) = newValue } } """ @@ -98,10 +98,10 @@ class ReadWritePropertyNode: PropertyNode, Equatable { declaration = """ public static override var \(escaped): \(dataTypeNode.swiftTypeName) { get { - return objectRef.\(escaped) + return jsObject.\(escaped) } set { - objectRef\(escaped) = newValue + jsObject\(escaped) = newValue } } """ @@ -114,7 +114,7 @@ class ReadWritePropertyNode: PropertyNode, Equatable { case (.classContext, true): declaration = """ - @ReadWriteAttribute(objectRef: Self.classRef, name: "\(name)") + @ReadWriteAttribute(jsObject: Self.constructor, name: "\(name)") public static var \(escaped): \(dataTypeNode.swiftTypeName) """ @@ -148,10 +148,10 @@ class ReadWritePropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(escaped).fromJSValue()! as \(dataTypeNode.typeErasedSwiftType) + return jsObject.\(escaped).fromJSValue()! as \(dataTypeNode.typeErasedSwiftType) } set { - objectRef.\(escaped) = newValue.jsValue()! + jsObject.\(escaped) = newValue.jsValue()! } } """ @@ -170,18 +170,18 @@ class ReadWritePropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - guard let function = objectRef.\(escaped).function else { + guard let function = jsObject.\(escaped).function else { return nil } return { (\(getterArguments)) in function(\(getterArguments)).fromJSValue()! } } set { if let newValue = newValue { - objectRef.\(escaped) = JSClosure { arguments in + jsObject.\(escaped) = JSClosure { arguments in return newValue(\(setterArguments)).jsValue() }.jsValue() } else { - objectRef.\(escaped) = .null + jsObject.\(escaped) = .null } } } @@ -198,11 +198,11 @@ class ReadWritePropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - let function = objectRef.\(escaped).function! + let function = jsObject.\(escaped).function! return { (\(getterArguments)) in function(\(getterArguments)).fromJSValue()! } } set { - objectRef.\(escaped) = JSClosure { arguments in + jsObject.\(escaped) = JSClosure { arguments in return newValue(\(setterArguments)).jsValue() }.jsValue() } @@ -217,10 +217,10 @@ class ReadWritePropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(escaped).fromJSValue()! + return jsObject.\(escaped).fromJSValue()! } set { - objectRef.\(escaped) = newValue.jsValue() + jsObject.\(escaped) = newValue.jsValue() } } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift index 1508c4b..b267a9f 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadonlyPropertyNode.swift @@ -22,7 +22,7 @@ class ReadonlyPropertyNode: PropertyNode, Equatable { } return """ - _\(name) = ReadonlyAttribute(objectRef: objectRef, name: "\(name)") + _\(name) = ReadonlyAttribute(jsObject: jsObject, name: "\(name)") """ } @@ -46,7 +46,7 @@ class ReadonlyPropertyNode: PropertyNode, Equatable { case (.classContext, true): declaration = """ - @ReadonlyAttribute(objectRef: Self.classRef, name: "\(name)") + @ReadonlyAttribute(jsObject: Self.constructor, name: "\(name)") public static var \(escapedName(name)): \(dataTypeNode.swiftTypeName) """ @@ -81,7 +81,7 @@ class ReadonlyPropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(name).fromJSValue()! as \(dataTypeNode.typeErasedSwiftType) + return jsObject.\(name).fromJSValue()! as \(dataTypeNode.typeErasedSwiftType) } } """ @@ -95,7 +95,7 @@ class ReadonlyPropertyNode: PropertyNode, Equatable { _swiftDeclarations(inContext: inContext) + """ { get { - return objectRef.\(name).fromJSValue()! + return jsObject.\(name).fromJSValue()! } } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift index abbdd31..3b7efea 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift @@ -70,9 +70,9 @@ class SubscriptNode: MemberNode, Equatable { let lookup: String declaration += " {\n" if isNamed { - lookup = "objectRef.\(escapedName(nameParameter.label))" + lookup = "jsObject.\(escapedName(nameParameter.label))" } else { - lookup = "objectRef[\(nameParameter.label)]" + lookup = "jsObject[\(nameParameter.label)]" } if returnTypeNode.isProtocol { diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift index 2ba2a8a..da92a2d 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift @@ -67,13 +67,13 @@ class ClassNode: TypeNode, Equatable { declaration = """ public class \(typeName): \(inheritance) { - public class var classRef: JSFunctionRef { JSObjectRef.global.\(typeName).function! } + public class var constructor: JSFunction { JSObject.global.\(typeName).function! } - public let objectRef: JSObjectRef + public let jsObject: JSObject - public required init(withCompatibleObject objectRef: JSObjectRef) { + public required init(withCompatibleObject jsObject: JSObject) { \(propertyNodes.compactMap { $0.initializationStatement(forContext: context) }.joined(separator: "\n")) - self.objectRef = objectRef + self.jsObject = jsObject } """ @@ -81,11 +81,11 @@ class ClassNode: TypeNode, Equatable { declaration = """ public class \(typeName): \(inheritance) { - public override class var classRef: JSFunctionRef { JSObjectRef.global.\(typeName).function! } + public override class var constructor: JSFunction { JSObject.global.\(typeName).function! } - public required init(withCompatibleObject objectRef: JSObjectRef) { + public required init(withCompatibleObject jsObject: JSObject) { \(propertyNodes.compactMap { $0.initializationStatement(forContext: context) }.joined(separator: "\n")) - super.init(withCompatibleObject: objectRef) + super.init(withCompatibleObject: jsObject) } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift index 5e51575..93abd44 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift @@ -31,8 +31,8 @@ class NamespaceNode: TypeNode, Equatable { var declaration = """ public enum \(typeName) { - public static var objectRef: JSObjectRef { - return JSObjectRef.global.\(typeName).object! + public static var jsObject: JSObject { + return JSObject.global.\(typeName).object! }\n """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift index 12b09f0..f0b4650 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift @@ -30,12 +30,12 @@ class TypeErasedWrapperStructNode: TypeNode, Equatable { var declaration = """ class \(swiftTypeName): JSBridgedClass, \(unwrapNode(wrapped).swiftTypeName) { - public class var classRef: JSFunctionRef { JSObjectRef.global.\(wrapped.identifier).function! } + public class var constructor: JSFunction { JSObject.global.\(wrapped.identifier).function! } - let objectRef: JSObjectRef + let jsObject: JSObject - required init(withCompatibleObject objectRef: JSObjectRef) { - self.objectRef = objectRef + required init(withCompatibleObject jsObject: JSObject) { + self.jsObject = jsObject } """ From 03bcb8ec79144c900a300f8164a8045199825dda Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Tue, 15 Sep 2020 12:47:42 -0400 Subject: [PATCH 06/22] Fix lint errors --- .../IntermediateRepresentation.swift | 9 +---- .../Member Nodes/MethodNode.swift | 37 ++++++++++++------- .../Type Nodes/ProtocolNode.swift | 12 +++++- 3 files changed, 35 insertions(+), 23 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift index 9ad9572..fb206e5 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift @@ -57,13 +57,6 @@ public class NodePointer: Hashable { } } -public enum ProtocolKind { - /// `callback interface` - case callback - /// `interface mixin` - case mixin -} - public class IntermediateRepresentation: Collection { public typealias Index = Swift.Dictionary.Index @@ -247,7 +240,7 @@ public class IntermediateRepresentation: Collection { } @discardableResult - func registerProtocol(withTypeName typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode], kind: ProtocolKind) -> NodePointer { + func registerProtocol(withTypeName typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode], kind: ProtocolNode.Kind) -> NodePointer { let nodePointer = existingOrNewNodePointer(for: typeName) let typeErasedPointer = existingOrNewNodePointer(for: "Any\(typeName)") diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift index 4511035..aafc1fe 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift @@ -34,28 +34,39 @@ class MethodNode: MemberNode, Equatable { } while removedParameter || parameters.contains(where: { $0.isOmittable && $0.defaultValue == nil }) for parameter in parameters { - let isOptional = parameter.dataType.node!.isOptional - guard let node = (isOptional ? (parameter.dataType.node as? OptionalNode)?.wrapped.node : parameter.dataType.node) as? ProtocolNode, - node.kind == .callback - else { continue } + let unwrapped: ProtocolNode + if let optional = parameter.dataType.node as? OptionalNode { + guard let node = optional.wrapped.node as? ProtocolNode else { continue } + unwrapped = node + } else { + guard let node = parameter.dataType.node as? ProtocolNode else { continue } + unwrapped = node + } + guard unwrapped.kind == .callback else { continue } for params in overloads { var params = params guard let idx = params.firstIndex(where: { $0.label == parameter.label }) else { continue } let param = params[idx] - let method = node.requiredMembers.first { $0.isMethod && !$0.isStatic && !$0.isSubscript } as! MethodNode + guard let method = unwrapped.requiredMembers.first(where: { $0.isMethod && !$0.isStatic && !$0.isSubscript }) as? MethodNode else { continue } let closureNode = ClosureNode(arguments: method.parameters.map { $0.dataType }, returnType: method.returnType) + let typeNode: TypeNode + + if let optional = parameter.dataType.node as? OptionalNode { + typeNode = OptionalNode( + wrapped: NodePointer( + identifier: optional.wrapped.identifier, + node: closureNode + ) + ) + } else { + typeNode = closureNode + } + params[idx] = ParameterNode( label: param.label, dataType: NodePointer( identifier: param.dataType.identifier, - node: isOptional - ? OptionalNode( - wrapped: NodePointer( - identifier: (param.dataType.node as! OptionalNode).wrapped.identifier, - node: closureNode - ) - ) - : closureNode + node: typeNode ), isVariadic: param.isVariadic, isOmittable: param.isOmittable, diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift index 51ec66a..5d7b468 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift @@ -8,12 +8,20 @@ class ProtocolNode: TypeNode, Equatable { let typeName: String var inheritsFrom: Set - let kind: ProtocolKind + let kind: Kind + + /// The kind of a protocol ProtocolNode + enum Kind { + /// `callback interface` + case callback + /// `interface mixin` + case mixin + } var requiredMembers: [MemberNode] var defaultImplementations: [MemberNode] - internal init(typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode], kind: ProtocolKind) { + internal init(typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode], kind: Kind) { self.typeName = typeName self.inheritsFrom = inheritsFrom self.requiredMembers = requiredMembers From 7d142e37d9300c577feca5754ed4324c90a1d164 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 15:55:09 -0400 Subject: [PATCH 07/22] Last updates for compatibility --- .../IntermediateRepresentation/IRGenerator.swift | 4 ++-- .../Member Nodes/ConstructorNode.swift | 2 +- .../Type Nodes/ClassNode.swift | 6 +++--- .../Type Nodes/DictionaryNode.swift | 16 +++++++--------- .../Type Nodes/TypeErasedWrapperStructNode.swift | 2 +- 5 files changed, 14 insertions(+), 16 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift index 83b3045..637e970 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift @@ -283,7 +283,7 @@ public class IRGenerator { case .distinguishableType(let distinguishableType): return handleDistinguishableType(distinguishableType) case .any: - return ir.registerBasicType(withTypeName: "AnyJSValueCodable") + return ir.registerBasicType(withTypeName: "JSValue") case .promiseType(let promise): let returnType = handleReturnType(promise.returnType) @@ -344,7 +344,7 @@ public class IRGenerator { return arrayNode case .object(let isNullable): - let nodePointer = ir.registerBasicType(withTypeName: "AnyJSValueCodable") + let nodePointer = ir.registerBasicType(withTypeName: "JSValue") if isNullable { return insertOptional(for: nodePointer) } diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift index 98f5b7c..db48117 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift @@ -123,7 +123,7 @@ class ConstructorNode: MemberNode, Equatable { } declaration += """ { - self.init(withCompatibleObject: \(className).constructor.new(\(passedParameters.joined(separator: ", ")))) + self.init(unsafelyWrapping: \(className).constructor.new(\(passedParameters.joined(separator: ", ")))) } """ } diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift index da92a2d..bedf918 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift @@ -71,7 +71,7 @@ class ClassNode: TypeNode, Equatable { public let jsObject: JSObject - public required init(withCompatibleObject jsObject: JSObject) { + public required init(unsafelyWrapping jsObject: JSObject) { \(propertyNodes.compactMap { $0.initializationStatement(forContext: context) }.joined(separator: "\n")) self.jsObject = jsObject } @@ -83,9 +83,9 @@ class ClassNode: TypeNode, Equatable { public override class var constructor: JSFunction { JSObject.global.\(typeName).function! } - public required init(withCompatibleObject jsObject: JSObject) { + public required init(unsafelyWrapping jsObject: JSObject) { \(propertyNodes.compactMap { $0.initializationStatement(forContext: context) }.joined(separator: "\n")) - super.init(withCompatibleObject: jsObject) + super.init(unsafelyWrapping: jsObject) } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift index b6f53d8..43799dd 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift @@ -68,24 +68,22 @@ class DictionaryNode: TypeNode, Equatable { case \(cases.map(escapedName).joined(separator: ", ")) } - public typealias Value = AnyJSValueCodable + private let dictionary: [String : JSValue] - private let dictionary: [String : AnyJSValueCodable] - - public init(uniqueKeysWithValues elements: [(Key, Value)]) { - self.dictionary = Dictionary(uniqueKeysWithValues: elements.map({ ($0.0.rawValue, $0.1) })) + public init(uniqueKeysWithValues elements: [(Key, JSValueConvertible)]) { + self.dictionary = Dictionary(uniqueKeysWithValues: elements.map({ ($0.0.rawValue, $0.1.jsValue()) })) } - public init(dictionaryLiteral elements: (Key, AnyJSValueCodable)...) { - self.dictionary = Dictionary(uniqueKeysWithValues: elements.map({ ($0.0.rawValue, $0.1) })) + public init(dictionaryLiteral elements: (Key, JSValueConvertible)...) { + self.dictionary = Dictionary(uniqueKeysWithValues: elements.map({ ($0.0.rawValue, $0.1.jsValue()) })) } - subscript(_ key: Key) -> AnyJSValueCodable? { + subscript(_ key: Key) -> JSValue? { dictionary[key.rawValue] } public init?(from value: JSValue) { - if let dictionary: [String : AnyJSValueCodable] = value.fromJSValue() { + if let dictionary: [String : JSValue] = value.fromJSValue() { self.dictionary = dictionary } return nil diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift index f0b4650..d3b64e7 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift @@ -34,7 +34,7 @@ class TypeErasedWrapperStructNode: TypeNode, Equatable { let jsObject: JSObject - required init(withCompatibleObject jsObject: JSObject) { + required init(unsafelyWrapping jsObject: JSObject) { self.jsObject = jsObject } From 91e3b147e46a0b5e1c3123a5fb808d29a171394b Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 15:55:28 -0400 Subject: [PATCH 08/22] Remove unnecessary fatalError in failable initializer --- .../Type Nodes/EnumerationWithAssociatedValuesNode.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift index b71e497..995047e 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/EnumerationWithAssociatedValuesNode.swift @@ -117,7 +117,7 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { initMap.append(""" { - fatalError() + return nil } """) From 30fe9e746cae44f34df56ea4193ab7e9bfcb2a65 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 16:01:16 -0400 Subject: [PATCH 09/22] Record the file name tokenization errors occurred in --- Sources/WebIDL/Tokenizer/Tokenizer.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/WebIDL/Tokenizer/Tokenizer.swift b/Sources/WebIDL/Tokenizer/Tokenizer.swift index 849748f..1beaffa 100644 --- a/Sources/WebIDL/Tokenizer/Tokenizer.swift +++ b/Sources/WebIDL/Tokenizer/Tokenizer.swift @@ -110,7 +110,7 @@ public enum Tokenizer { guard let string = String(data: fileData, encoding: .utf8) else { return nil } - return try tokenize(string) + return try tokenize(string, name: fileURL.lastPathComponent) } // swiftlint:disable cyclomatic_complexity function_body_length @@ -118,7 +118,7 @@ public enum Tokenizer { /// - Parameter string: A string containing Web IDL definitions. /// - Throws: Any error related to the file operations or the tokenization operation. /// - Returns: A `TokenisationResult` instance containing the token stream for the given file. - public static func tokenize(_ string: String) throws -> TokenisationResult { + public static func tokenize(_ string: String, name: String = "") throws -> TokenisationResult { var tokens = Tokens() @@ -179,7 +179,7 @@ public enum Tokenizer { tokens.append(.other) others.append(buffer) } else { - print("Undefined sequence: \(buffer)") + print("[\(name)] Undefined sequence: \(buffer)") } reset() } From 6880d9d05a73bb822eef9c3c20108878e2c3f9cc Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 16:58:07 -0400 Subject: [PATCH 10/22] Address spec update that replaces void with undefined --- .../IRGenerator.swift | 66 ++++++++----------- Sources/WebIDL/Parser/Models.swift | 24 +++---- Sources/WebIDL/Parser/Parser.swift | 50 +++++--------- Sources/WebIDL/Tokenizer/NonTerminal.swift | 1 - Sources/WebIDL/Tokenizer/Terminal.swift | 2 +- Tests/webidl2swiftTests/ParserTests.swift | 18 ++--- 6 files changed, 67 insertions(+), 94 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift index 637e970..e9214c3 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift @@ -75,7 +75,7 @@ public class IRGenerator { case .regularOperation(let regularOperation, _): return handleRegularOperation(regularOperation) case .readonlyAttribute(let attributeRest): - let dataType = handleDataType(attributeRest.typeWithExtendedAttributes.dataType) + let dataType = handleType(attributeRest.typeWithExtendedAttributes.type) let name = handleAttributeName(attributeRest.attributeName) return ReadonlyPropertyNode(name: name, dataType: dataType, isStatic: false) } @@ -126,12 +126,12 @@ public class IRGenerator { return nil case .readOnlyAttributeRest(false, let attributeRest, _): - let type = handleDataType(attributeRest.typeWithExtendedAttributes.dataType) + let type = handleType(attributeRest.typeWithExtendedAttributes.type) let name = handleAttributeName(attributeRest.attributeName) return ReadWritePropertyNode(name: name, dataType: type, isOverride: false, isStatic: false) case .readOnlyAttributeRest(true, let attributeRest, _): - let type = handleDataType(attributeRest.typeWithExtendedAttributes.dataType) + let type = handleType(attributeRest.typeWithExtendedAttributes.type) let name = handleAttributeName(attributeRest.attributeName) return ReadonlyPropertyNode(name: name, dataType: type, isStatic: false) } @@ -147,14 +147,14 @@ public class IRGenerator { func handleCallback(_ callback: Callback) { - let returnType = handleReturnType(callback.returnType) + let returnType = handleType(callback.returnType) let arguments: [NodePointer] = callback.argumentList.map { switch $0.rest { case .optional(let typeWithExtendedAttributes, _, _): - return handleDataType(typeWithExtendedAttributes.dataType) + return handleType(typeWithExtendedAttributes.type) case .nonOptional(let dataType, _, _): - return handleDataType(dataType) + return handleType(dataType) } } @@ -227,7 +227,7 @@ public class IRGenerator { func handleTypedef(_ typedef: Typedef) { - let dataType = handleDataType(typedef.dataType) + let dataType = handleType(typedef.type) _ = ir.registerAliasNode(withTypeName: typedef.identifier, aliasing: unwrapNode(dataType)) } @@ -262,9 +262,9 @@ public class IRGenerator { ir.registerBasicType(withTypeName: "String") } - func handleDataType(_ dataType: DataType) -> NodePointer { + func handleType(_ type: Type) -> NodePointer { - switch dataType { + switch type { case .single(let singleType): return handleSingleType(singleType) @@ -282,11 +282,14 @@ public class IRGenerator { switch singleType { case .distinguishableType(let distinguishableType): return handleDistinguishableType(distinguishableType) + case .any: return ir.registerBasicType(withTypeName: "JSValue") + case .undefined: + return ir.registerBasicType(withTypeName: "Void") case .promiseType(let promise): - let returnType = handleReturnType(promise.returnType) + let returnType = handleType(promise.returnType) return ir.registerBasicType(withTypeName: "Promise<\(returnType.identifier)>") } } @@ -335,7 +338,7 @@ public class IRGenerator { return nodePointer case .sequence(let typeWithExtendedAttributes, let isNullable): - let type = handleDataType(typeWithExtendedAttributes.dataType) + let type = handleType(typeWithExtendedAttributes.type) let arrayNode = ir.registerArrayNode(withTypeName: "\(type.identifier)Sequence", element: type) if isNullable { @@ -378,7 +381,7 @@ public class IRGenerator { case .bufferRelated(.Float64Array, let isNullable): return handleBufferRelatedWithScalarType("Float64Array", "Double", isNullable) case .frozenArray(let typeWithExtendedAttributes, let isNullable): - let type = handleDataType(typeWithExtendedAttributes.dataType) + let type = handleType(typeWithExtendedAttributes.type) let name = "\(type.identifier)Array" let arrayNode = ArrayNode(element: type) let aliasPointer = ir.registerAliasNode(withTypeName: name, aliasing: arrayNode) @@ -395,7 +398,7 @@ public class IRGenerator { func handleRecordType(_ recordType: RecordType) -> NodePointer { - let valueType = handleDataType(recordType.typeWithExtendedAttributes.dataType) + let valueType = handleType(recordType.typeWithExtendedAttributes.type) let name = "\(valueType.identifier)Record" let recordNode = RecordNode(value: valueType) let aliasPointer = ir.registerAliasNode(withTypeName: name, aliasing: recordNode) @@ -428,7 +431,7 @@ public class IRGenerator { switch readOnlyMember { case .attribute(let attribute): let name = handleAttributeName(attribute.attributeName) - let type = handleDataType(attribute.typeWithExtendedAttributes.dataType) + let type = handleType(attribute.typeWithExtendedAttributes.type) return ReadonlyPropertyNode(name: name, dataType: type, isStatic: false) @@ -497,7 +500,7 @@ public class IRGenerator { return handleRegularOperation(regularOperation) case .special(let special, let regularOperation): - let returnType = handleReturnType(regularOperation.returnType) + let returnType = handleType(regularOperation.returnType) let parameters = handleArgumentList(regularOperation.argumentList) switch special { case .getter: @@ -518,7 +521,7 @@ public class IRGenerator { switch argument.rest { case .optional(let typeWithExtendedAttributes, let label, .some(let defaultValue)): - let dataType = handleDataType(typeWithExtendedAttributes.dataType) + let dataType = handleType(typeWithExtendedAttributes.type) return ParameterNode(label: handleArgumentName(label), dataType: dataType, isVariadic: false, @@ -527,14 +530,14 @@ public class IRGenerator { case .optional(let typeWithExtendedAttributes, let label, .none): return ParameterNode(label: handleArgumentName(label), - dataType: handleDataType(typeWithExtendedAttributes.dataType), + dataType: handleType(typeWithExtendedAttributes.type), isVariadic: false, isOmittable: true, defaultValue: nil) case .nonOptional(let dataType, let ellipsis, let label): return ParameterNode(label: handleArgumentName(label), - dataType: handleDataType(dataType), + dataType: handleType(dataType), isVariadic: ellipsis, isOmittable: ellipsis, defaultValue: nil) @@ -546,7 +549,7 @@ public class IRGenerator { if let operationName = regularOperation.operationName { let name = handleOperationName(operationName) - let returnType = handleReturnType(regularOperation.returnType) + let returnType = handleType(regularOperation.returnType) return MethodNode(name: name, returnType: returnType, parameters: handleArgumentList(regularOperation.argumentList)) } else { @@ -565,17 +568,6 @@ public class IRGenerator { } } - func handleReturnType(_ returnType: ReturnType) -> NodePointer { - - switch returnType { - case .void: - return ir.registerBasicType(withTypeName: "Void") - - case .dataType(let dataType): - return handleDataType(dataType) - } - } - func handleUnsignedIntegerType(_ integerType: UnsignedIntegerType) -> NodePointer { guard !useSimpleTypes else { @@ -631,13 +623,13 @@ public class IRGenerator { switch readWriteAttribute { case .inherit(let attributeRest): - let type = handleDataType(attributeRest.typeWithExtendedAttributes.dataType) + let type = handleType(attributeRest.typeWithExtendedAttributes.type) let name = handleAttributeName(attributeRest.attributeName) return ReadWritePropertyNode(name: name, dataType: type, isOverride: true, isStatic: false) case .notInherit(let attributeRest): - let type = handleDataType(attributeRest.typeWithExtendedAttributes.dataType) + let type = handleType(attributeRest.typeWithExtendedAttributes.type) let name = handleAttributeName(attributeRest.attributeName) return ReadWritePropertyNode(name: name, dataType: type, isOverride: false, isStatic: false) @@ -662,12 +654,12 @@ public class IRGenerator { func handleIterable(_ iterable: Iterable) -> MemberNode { - switch (iterable.typeWithExtendedAttributes0.dataType, iterable.typeWithExtendedAttributes1?.dataType) { + switch (iterable.typeWithExtendedAttributes0.type, iterable.typeWithExtendedAttributes1?.type) { case (_, let second?): - return PairIterableNode(dataType: handleDataType(second)) + return PairIterableNode(dataType: handleType(second)) case (let first, nil): - return ValueIterableNode(dataType: handleDataType(first)) + return ValueIterableNode(dataType: handleType(first)) } } @@ -675,13 +667,13 @@ public class IRGenerator { switch staticMember { case .readOnlyAttributeRest(false, let attributeRest): - let type = handleDataType(attributeRest.typeWithExtendedAttributes.dataType) + let type = handleType(attributeRest.typeWithExtendedAttributes.type) let name = handleAttributeName(attributeRest.attributeName) return ReadWritePropertyNode(name: name, dataType: type, isOverride: false, isStatic: true) case .readOnlyAttributeRest(true, let attributeRest): - let type = handleDataType(attributeRest.typeWithExtendedAttributes.dataType) + let type = handleType(attributeRest.typeWithExtendedAttributes.type) let name = handleAttributeName(attributeRest.attributeName) return ReadonlyPropertyNode(name: name, dataType: type, isStatic: true) diff --git a/Sources/WebIDL/Parser/Models.swift b/Sources/WebIDL/Parser/Models.swift index 7a28045..a98534b 100644 --- a/Sources/WebIDL/Parser/Models.swift +++ b/Sources/WebIDL/Parser/Models.swift @@ -23,7 +23,7 @@ public struct Callback: Definition, Equatable { public let identifier: String public let extendedAttributeList: ExtendedAttributeList - public let returnType: ReturnType + public let returnType: Type public let argumentList: [Argument] } @@ -114,7 +114,7 @@ public struct DictionaryMember: Equatable { public let isRequired: Bool public let extendedAttributeList: ExtendedAttributeList - public let dataType: DataType + public let type: Type public let extendedAttributesOfDataType: ExtendedAttributeList? public let defaultValue: DefaultValue? } @@ -164,7 +164,7 @@ public enum Operation: Equatable { public struct RegularOperation: Equatable { - public let returnType: ReturnType + public let returnType: Type public let operationName: OperationName? public let argumentList: [Argument] } @@ -194,7 +194,7 @@ public struct Argument: Equatable { public indirect enum ArgumentRest: Equatable { case optional(TypeWithExtendedAttributes, ArgumentName, DefaultValue?) - case nonOptional(DataType, _ ellipsis: Bool, ArgumentName) + case nonOptional(Type, _ ellipsis: Bool, ArgumentName) } public enum ArgumentName: Equatable { @@ -225,7 +225,7 @@ public struct MaplikeRest: Equatable { } public struct SetlikeRest: Equatable { - public let dataType: TypeWithExtendedAttributes + public let elementType: TypeWithExtendedAttributes } public enum DefaultValue: Equatable { @@ -266,17 +266,17 @@ public struct IncludesStatement: Definition, Equatable { public struct Typedef: Definition, Equatable { public let identifier: String - public let dataType: DataType + public let type: Type public let extendedAttributeList: ExtendedAttributeList } public struct TypeWithExtendedAttributes: Equatable { - public let dataType: DataType + public let type: Type public let extendedAttributeList: ExtendedAttributeList } -public indirect enum DataType: Equatable { +public indirect enum Type: Equatable { case single(SingleType) case union([UnionMemberType], Bool) } @@ -285,6 +285,7 @@ public indirect enum SingleType: Equatable { case distinguishableType(DistinguishableType) case any + case undefined case promiseType(Promise) } @@ -321,11 +322,6 @@ public struct AsyncIterable: Equatable { public let typeWithExtendedAttributes1: TypeWithExtendedAttributes } -public enum ReturnType: Equatable { - case void - case dataType(DataType) -} - public enum ReadWriteAttribute: Equatable { case inherit(AttributeRest) case notInherit(AttributeRest) @@ -333,7 +329,7 @@ public enum ReadWriteAttribute: Equatable { public struct Promise: Equatable { - public let returnType: ReturnType + public let returnType: Type } // swiftlint:disable identifier_name diff --git a/Sources/WebIDL/Parser/Parser.swift b/Sources/WebIDL/Parser/Parser.swift index 25a5742..46c218d 100644 --- a/Sources/WebIDL/Parser/Parser.swift +++ b/Sources/WebIDL/Parser/Parser.swift @@ -484,7 +484,7 @@ public class Parser { let identifier = try parseIdentifier() try expect(next: .terminal(.equalSign)) - let returnType = try parseReturnType() + let returnType = try parseType() try expect(next: .terminal(.openingParenthesis)) let argumentList = try parseArgumentList() try expect(next: .terminal(.closingParenthesis)) @@ -716,10 +716,10 @@ public class Parser { /* RegularOperation :: - ReturnType OperationRest + Type OperationRest */ - let returnType = try parseReturnType() + let returnType = try parseType() let operationRest = try parseOperationRest() return RegularOperation(returnType: returnType, operationName: operationRest.optioalOperationName, argumentList: operationRest.argumentList) @@ -1055,7 +1055,7 @@ public class Parser { try expect(next: .terminal(.closingAngleBracket)) try expect(next: .terminal(.semicolon)) - return SetlikeRest(dataType: typeWithExtendedAttributes) + return SetlikeRest(elementType: typeWithExtendedAttributes) } func parseReadWriteAttribute(extendedAttributeList: ExtendedAttributeList) throws -> InterfaceMember { @@ -1497,7 +1497,7 @@ public class Parser { return DictionaryMember(identifier: identifier, isRequired: true, extendedAttributeList: extendedAttributeList, - dataType: typeWithExtendedAttributes.dataType, + type: typeWithExtendedAttributes.type, extendedAttributesOfDataType: typeWithExtendedAttributes.extendedAttributeList, defaultValue: nil) @@ -1509,7 +1509,7 @@ public class Parser { return DictionaryMember(identifier: identifier, isRequired: false, extendedAttributeList: extendedAttributeList, - dataType: dataType, + type: dataType, extendedAttributesOfDataType: nil, defaultValue: defaultValue) @@ -1585,7 +1585,7 @@ public class Parser { let identifier = try parseIdentifier() try expect(next: .terminal(.semicolon)) - return Typedef(identifier: identifier, dataType: typeWithExtendedAttributes.dataType, extendedAttributeList: typeWithExtendedAttributes.extendedAttributeList) + return Typedef(identifier: identifier, type: typeWithExtendedAttributes.type, extendedAttributeList: typeWithExtendedAttributes.extendedAttributeList) } func parseTypeWithExtendedAttributes() throws -> TypeWithExtendedAttributes { @@ -1597,10 +1597,10 @@ public class Parser { let extendedAttributeList = try parseExtendedAttributeList() let dataType = try parseType() - return .init(dataType: dataType, extendedAttributeList: extendedAttributeList) + return .init(type: dataType, extendedAttributeList: extendedAttributeList) } - func parseType() throws -> DataType { + func parseType() throws -> Type { /* Type :: @@ -1626,6 +1626,7 @@ public class Parser { SingleType :: DistinguishableType any + undefinedå PromiseType */ @@ -1638,6 +1639,10 @@ public class Parser { tokens.removeFirst() return .any + case .terminal(.undefined): + tokens.removeFirst() + return .undefined + case let token where firstSet(for: .PromiseType).contains(token): let promise = try parsePromiseType() return .promiseType(promise) @@ -1934,29 +1939,17 @@ public class Parser { func parsePromiseType() throws -> Promise { /* PromiseType :: - Promise < ReturnType > + Promise < Type > */ try expect(next: .terminal(.promise)) try expect(next: .terminal(.openingAngleBracket)) - let returnType = try parseReturnType() + let returnType = try parseType() try expect(next: .terminal(.closingAngleBracket)) return Promise(returnType: returnType) } - func parseReturnType() throws -> ReturnType { - /* - ReturnType :: - Type - void - */ - if check(forNext: .terminal(.void)) { - return .void - } else { - return .dataType(try parseType()) - } - } func parseRecordType() throws -> RecordType { /* @@ -2268,7 +2261,7 @@ func firstSet(for symbol: NonTerminal) -> Set { ) case .RegularOperation: - return firstSet(for: .ReturnType) + return firstSet(for: .Type) case .SpecialOperation: return firstSet(for: .Special) @@ -2325,12 +2318,6 @@ func firstSet(for symbol: NonTerminal) -> Set { case .Ellipsis: return [.terminal(.ellipsis)] - case .ReturnType: - return union( - firstSet(for: .Type), - [.terminal(.void)] - ) - case .Constructor: return [.terminal(.constructor)] @@ -2448,7 +2435,7 @@ func firstSet(for symbol: NonTerminal) -> Set { case .SingleType: return union( firstSet(for: .DistinguishableType), - [.terminal(.any)], + [.terminal(.any), .terminal(.undefined)], firstSet(for: .PromiseType) ) @@ -2618,7 +2605,6 @@ func firstSet(for symbol: NonTerminal) -> Set { .terminal(.symbol), .terminal(.true), .terminal(.unsigned), - .terminal(.void), ] return union( terminals, diff --git a/Sources/WebIDL/Tokenizer/NonTerminal.swift b/Sources/WebIDL/Tokenizer/NonTerminal.swift index bfe290b..b4ca4c7 100644 --- a/Sources/WebIDL/Tokenizer/NonTerminal.swift +++ b/Sources/WebIDL/Tokenizer/NonTerminal.swift @@ -60,7 +60,6 @@ public enum NonTerminal: String, Equatable, CustomStringConvertible { case ArgumentRest = "ArgumentRest" case ArgumentName = "ArgumentName" case Ellipsis = "Ellipsis" - case ReturnType = "ReturnType" case Constructor = "Constructor" case Stringifier = "Stringifier" case StringifierRest = "StringifierRest" diff --git a/Sources/WebIDL/Tokenizer/Terminal.swift b/Sources/WebIDL/Tokenizer/Terminal.swift index 62c8954..6e082e5 100644 --- a/Sources/WebIDL/Tokenizer/Terminal.swift +++ b/Sources/WebIDL/Tokenizer/Terminal.swift @@ -82,7 +82,7 @@ public enum Terminal: String, Equatable, CustomStringConvertible { case unsigned = "unsigned" case short = "short" case long = "long" - case void = "void" + case undefined = "undefined" case ArrayBuffer = "ArrayBuffer" case DataView = "DataView" diff --git a/Tests/webidl2swiftTests/ParserTests.swift b/Tests/webidl2swiftTests/ParserTests.swift index 33cafa5..4c02bc8 100644 --- a/Tests/webidl2swiftTests/ParserTests.swift +++ b/Tests/webidl2swiftTests/ParserTests.swift @@ -99,15 +99,15 @@ final class ParserTests: XCTestCase { let parser = Parser(input: result) let definitions = try parser.parse() - let domStringType: DataType = .single(.distinguishableType(.string(.DOMString, false))) - let longlongType: DataType = .single(.distinguishableType(.primitive(.UnsignedIntegerType(.signed(.longLong)), false))) + let domStringType: Type = .single(.distinguishableType(.string(.DOMString, false))) + let longlongType: Type = .single(.distinguishableType(.primitive(.UnsignedIntegerType(.signed(.longLong)), false))) XCTAssertEqual(definitions as! [Dictionary], [ Dictionary(identifier: "A", extendedAttributeList: [], inheritance: nil, members: [ - .init(identifier: "a", isRequired: true, extendedAttributeList: [], dataType: domStringType, extendedAttributesOfDataType: [], defaultValue: nil) + .init(identifier: "a", isRequired: true, extendedAttributeList: [], type: domStringType, extendedAttributesOfDataType: [], defaultValue: nil) ]), Dictionary(identifier: "B", extendedAttributeList: [], inheritance: .init(identifier: "A"), members: [ - .init(identifier: "b", isRequired: false, extendedAttributeList: [], dataType: longlongType, extendedAttributesOfDataType: nil, defaultValue: .constValue(.integer(42))) + .init(identifier: "b", isRequired: false, extendedAttributeList: [], type: longlongType, extendedAttributesOfDataType: nil, defaultValue: .constValue(.integer(42))) ]), ]) } @@ -142,7 +142,7 @@ final class ParserTests: XCTestCase { ] XCTAssertEqual(definitions as! [Typedef], [ - Typedef(identifier: "String", dataType: .union(unionTypes, false), extendedAttributeList: []) + Typedef(identifier: "String", type: .union(unionTypes, false), extendedAttributeList: []) ]) } @@ -163,7 +163,7 @@ final class ParserTests: XCTestCase { let result = try Tokenizer.tokenize(""" callback interface A { - void handle(any... data); + undefined handle(any... data); }; """) let parser = Parser(input: result) @@ -171,7 +171,7 @@ final class ParserTests: XCTestCase { XCTAssertEqual(definitions as! [CallbackInterface], [ CallbackInterface(identifer: "A", extendedAttributeList: [], callbackInterfaceMembers: [ - .regularOperation(.init(returnType: .void, operationName: .identifier("handle"), argumentList: [.init(rest: .nonOptional(.single(.any), true, .identifier("data")), extendedAttributeList: [])]), []) + .regularOperation(.init(returnType: .single(.undefined), operationName: .identifier("handle"), argumentList: [.init(rest: .nonOptional(.single(.any), true, .identifier("data")), extendedAttributeList: [])]), []) ]) ]) } @@ -179,13 +179,13 @@ final class ParserTests: XCTestCase { func test_parseCallbackFunction() throws { let result = try Tokenizer.tokenize(""" - callback CallbackHandler = void (); + callback CallbackHandler = undefined (); """) let parser = Parser(input: result) let definitions = try parser.parse() XCTAssertEqual(definitions as! [Callback], [ - Callback(identifier: "CallbackHandler", extendedAttributeList: [], returnType: .void, argumentList: []) + Callback(identifier: "CallbackHandler", extendedAttributeList: [], returnType: .single(.undefined), argumentList: []) ]) } } From b0ea653ba1e53ee7221c3f9b12975ff0681c2f28 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 17:24:25 -0400 Subject: [PATCH 11/22] Update Parser.swift --- Sources/WebIDL/Parser/Models.swift | 2 +- Sources/WebIDL/Parser/Parser.swift | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/Sources/WebIDL/Parser/Models.swift b/Sources/WebIDL/Parser/Models.swift index a98534b..806fcff 100644 --- a/Sources/WebIDL/Parser/Models.swift +++ b/Sources/WebIDL/Parser/Models.swift @@ -319,7 +319,7 @@ public struct Iterable: Equatable { public struct AsyncIterable: Equatable { public let typeWithExtendedAttributes0: TypeWithExtendedAttributes - public let typeWithExtendedAttributes1: TypeWithExtendedAttributes + public let typeWithExtendedAttributes1: TypeWithExtendedAttributes? } public enum ReadWriteAttribute: Equatable { diff --git a/Sources/WebIDL/Parser/Parser.swift b/Sources/WebIDL/Parser/Parser.swift index 46c218d..54d72ad 100644 --- a/Sources/WebIDL/Parser/Parser.swift +++ b/Sources/WebIDL/Parser/Parser.swift @@ -982,18 +982,17 @@ public class Parser { /* AsyncIterable :: - async iterable < TypeWithExtendedAttributes , TypeWithExtendedAttributes > ; + async iterable < TypeWithExtendedAttributes OptionalType > ; */ try expect(next: .terminal(.async)) try expect(next: .terminal(.iterable)) try expect(next: .terminal(.openingAngleBracket)) - let typeWithExtendedAttributes0 = try parseTypeWithExtendedAttributes() - try expect(next: .terminal(.comma)) - let typeWithExtendedAttribute1 = try parseTypeWithExtendedAttributes() + let typeWithExtendedAttributes = try parseTypeWithExtendedAttributes() + let optionalType = try parseOptionalType() try expect(next: .terminal(.closingAngleBracket)) try expect(next: .terminal(.semicolon)) - return AsyncIterable(typeWithExtendedAttributes0: typeWithExtendedAttributes0, typeWithExtendedAttributes1: typeWithExtendedAttribute1) + return AsyncIterable(typeWithExtendedAttributes0: typeWithExtendedAttributes, typeWithExtendedAttributes1: optionalType) } func parseReadOnlyMember(extendedAttributeList: ExtendedAttributeList) throws -> InterfaceMember { From 69b6f8ba30bf73a4d4cdebb2c45f786588474280 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 17:29:56 -0400 Subject: [PATCH 12/22] Fixes to asynciterable --- Sources/WebIDL/Parser/Models.swift | 1 + Sources/WebIDL/Parser/Parser.swift | 12 ++++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Sources/WebIDL/Parser/Models.swift b/Sources/WebIDL/Parser/Models.swift index 806fcff..d65edbc 100644 --- a/Sources/WebIDL/Parser/Models.swift +++ b/Sources/WebIDL/Parser/Models.swift @@ -320,6 +320,7 @@ public struct AsyncIterable: Equatable { public let typeWithExtendedAttributes0: TypeWithExtendedAttributes public let typeWithExtendedAttributes1: TypeWithExtendedAttributes? + public let argumentList: [Argument]? } public enum ReadWriteAttribute: Equatable { diff --git a/Sources/WebIDL/Parser/Parser.swift b/Sources/WebIDL/Parser/Parser.swift index 54d72ad..8549698 100644 --- a/Sources/WebIDL/Parser/Parser.swift +++ b/Sources/WebIDL/Parser/Parser.swift @@ -982,7 +982,7 @@ public class Parser { /* AsyncIterable :: - async iterable < TypeWithExtendedAttributes OptionalType > ; + async iterable < TypeWithExtendedAttributes OptionalType > OptionalArgumentList; */ try expect(next: .terminal(.async)) try expect(next: .terminal(.iterable)) @@ -990,9 +990,17 @@ public class Parser { let typeWithExtendedAttributes = try parseTypeWithExtendedAttributes() let optionalType = try parseOptionalType() try expect(next: .terminal(.closingAngleBracket)) + let optionalArgumentList = try parseOptionalArgumentList() try expect(next: .terminal(.semicolon)) - return AsyncIterable(typeWithExtendedAttributes0: typeWithExtendedAttributes, typeWithExtendedAttributes1: optionalType) + return AsyncIterable(typeWithExtendedAttributes0: typeWithExtendedAttributes, typeWithExtendedAttributes1: optionalType, argumentList: optionalArgumentList) + } + + func parseOptionalArgumentList() throws -> [Argument]? { + guard check(forNext: .terminal(.openingParenthesis)) else { + return nil + } + return try parseArgumentList() } func parseReadOnlyMember(extendedAttributeList: ExtendedAttributeList) throws -> InterfaceMember { From d02606891c0171b711148a2c7ff25f4e5bad24f5 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 17:32:29 -0400 Subject: [PATCH 13/22] Update Parser.swift --- Sources/WebIDL/Parser/Parser.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Sources/WebIDL/Parser/Parser.swift b/Sources/WebIDL/Parser/Parser.swift index 8549698..9559aba 100644 --- a/Sources/WebIDL/Parser/Parser.swift +++ b/Sources/WebIDL/Parser/Parser.swift @@ -1000,7 +1000,10 @@ public class Parser { guard check(forNext: .terminal(.openingParenthesis)) else { return nil } - return try parseArgumentList() + try expect(next: .terminal(.openingParenthesis)) + let argumentList = try parseArgumentList() + try expect(next: .terminal(.closingParenthesis)) + return try argumentList } func parseReadOnlyMember(extendedAttributeList: ExtendedAttributeList) throws -> InterfaceMember { From d7614b44223b0e675b0ac0018fa79c217890f142 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 17:34:11 -0400 Subject: [PATCH 14/22] Update Parser.swift --- Sources/WebIDL/Parser/Parser.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Sources/WebIDL/Parser/Parser.swift b/Sources/WebIDL/Parser/Parser.swift index 9559aba..858978a 100644 --- a/Sources/WebIDL/Parser/Parser.swift +++ b/Sources/WebIDL/Parser/Parser.swift @@ -1000,10 +1000,9 @@ public class Parser { guard check(forNext: .terminal(.openingParenthesis)) else { return nil } - try expect(next: .terminal(.openingParenthesis)) let argumentList = try parseArgumentList() try expect(next: .terminal(.closingParenthesis)) - return try argumentList + return argumentList } func parseReadOnlyMember(extendedAttributeList: ExtendedAttributeList) throws -> InterfaceMember { From 76f1e87116f827fef0d5e85939192ca4086c22a4 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Sun, 20 Sep 2020 17:36:18 -0400 Subject: [PATCH 15/22] Update IntermediateRepresentation.swift --- .../IntermediateRepresentation/IntermediateRepresentation.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift index fb206e5..e15749d 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift @@ -265,7 +265,7 @@ public class IntermediateRepresentation: Collection { let nodePointer = existingOrNewNodePointer(for: typeName) if let alreadyRegisterd = nodePointer.node { guard let existingClass = alreadyRegisterd as? ClassNode else { - fatalError("Type mismatch for already registered Type!") + fatalError("Type mismatch for already registered Type \(typeName): \(type(of: alreadyRegisterd)) -> Class!") } existingClass.inheritsFrom.formUnion(inheritsFrom) existingClass.members.append(contentsOf: members) From 083563127e3c68b3bc54d9dc9f3323de0833893f Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Thu, 1 Oct 2020 10:32:54 -0400 Subject: [PATCH 16/22] =?UTF-8?q?Sort=20list=20of=20undefined=20types=20so?= =?UTF-8?q?=20it=E2=80=99s=20stable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/Commands/GenerateCode.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Commands/GenerateCode.swift b/Sources/Commands/GenerateCode.swift index c6613ac..0354c7a 100644 --- a/Sources/Commands/GenerateCode.swift +++ b/Sources/Commands/GenerateCode.swift @@ -74,7 +74,7 @@ public struct GenerateCode: ParsableCommand { guard undefinedTypes.isEmpty else { print("Error: The following types are undefined:") - print(undefinedTypes.map { "\t- \($0.0)" }.joined(separator: "\n")) + print(undefinedTypes.map { "\t- \($0.0)" }.sorted().joined(separator: "\n")) Self.exit(withError: ExitCode.failure) } From b697d9ee9d968e05cf1b912d6412c9344df23026 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Thu, 1 Oct 2020 10:33:23 -0400 Subject: [PATCH 17/22] Throw a fatalError when a member type is unimplemented --- Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift index e9214c3..bb6c1eb 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift @@ -195,7 +195,7 @@ public class IRGenerator { case .asyncIterable, .readWriteMaplike, .readWriteSetlike: - // Not implemented yet. + fatalError("Member type \(member) not yet implemented") return nil } } From 6381201d931943eec9e76126b0bf1404905969fc Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Thu, 1 Oct 2020 10:35:53 -0400 Subject: [PATCH 18/22] Add updates from review --- .../IntermediateRepresentation/Member Nodes/MethodNode.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift index aafc1fe..86e065d 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift @@ -20,6 +20,7 @@ class MethodNode: MemberNode, Equatable { true } + // swiftlint:disable cyclomatic_complexity function_body_length private func _generateOverloads() -> [[ParameterNode]] { var parameters = self.parameters var removedParameter = false @@ -173,7 +174,7 @@ class MethodNode: MemberNode, Equatable { closureOptional = false } else if let aliasNode = dataTypeNode as? AliasNode, let optionalNode = aliasNode.aliased as? OptionalNode, let cNode = optionalNode.wrapped.node as? ClosureNode { closureNode = cNode - closureOptional = false // FIXME: or true? + closureOptional = true } else if let optionalNode = dataTypeNode as? OptionalNode, let cNode = optionalNode.wrapped.node as? ClosureNode { closureNode = cNode closureOptional = true From c157325c31bc6e5c76443f6d068a91f603a48fa1 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Thu, 1 Oct 2020 10:44:10 -0400 Subject: [PATCH 19/22] =?UTF-8?q?void=20=E2=86=92=20undefined?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Example/WebIDL-files/CommonDefinitions.webidl | 2 +- Example/WebIDL-files/DOMStringMap.webidl | 4 +- Example/WebIDL-files/FileAPI.webidl | 12 +-- Example/WebIDL-files/FormData.webidl | 10 +-- Example/WebIDL-files/HTMLFormElement.webidl | 12 +-- Example/WebIDL-files/HTMLOrSVGElement.webidl | 4 +- Example/WebIDL-files/console.webidl | 38 ++++---- Example/WebIDL-files/dom.webidl | 88 +++++++++---------- 8 files changed, 85 insertions(+), 85 deletions(-) diff --git a/Example/WebIDL-files/CommonDefinitions.webidl b/Example/WebIDL-files/CommonDefinitions.webidl index d1dabfa..eb78bc5 100644 --- a/Example/WebIDL-files/CommonDefinitions.webidl +++ b/Example/WebIDL-files/CommonDefinitions.webidl @@ -44,4 +44,4 @@ typedef unsigned long long DOMTimeStamp; callback Function = any (any... arguments); -callback VoidFunction = void (); +callback VoidFunction = undefined (); diff --git a/Example/WebIDL-files/DOMStringMap.webidl b/Example/WebIDL-files/DOMStringMap.webidl index 5b60130..d81a086 100644 --- a/Example/WebIDL-files/DOMStringMap.webidl +++ b/Example/WebIDL-files/DOMStringMap.webidl @@ -1,6 +1,6 @@ interface DOMStringMap { getter DOMString (DOMString name); - [CEReactions] setter void (DOMString name, DOMString value); - [CEReactions] deleter void (DOMString name); + [CEReactions] setter undefined (DOMString name, DOMString value); + [CEReactions] deleter undefined (DOMString name); }; diff --git a/Example/WebIDL-files/FileAPI.webidl b/Example/WebIDL-files/FileAPI.webidl index c92c76e..b980a47 100644 --- a/Example/WebIDL-files/FileAPI.webidl +++ b/Example/WebIDL-files/FileAPI.webidl @@ -49,12 +49,12 @@ interface FileList { interface FileReader: EventTarget { constructor(); // async read methods - void readAsArrayBuffer(Blob blob); - void readAsBinaryString(Blob blob); - void readAsText(Blob blob, optional DOMString encoding); - void readAsDataURL(Blob blob); + undefined readAsArrayBuffer(Blob blob); + undefined readAsBinaryString(Blob blob); + undefined readAsText(Blob blob, optional DOMString encoding); + undefined readAsDataURL(Blob blob); - void abort(); + undefined abort(); // states const unsigned short EMPTY = 0; @@ -91,5 +91,5 @@ interface FileReaderSync { [Exposed=(Window,DedicatedWorker,SharedWorker)] partial interface URL { static DOMString createObjectURL((Blob or MediaSource) obj); - static void revokeObjectURL(DOMString url); + static undefined revokeObjectURL(DOMString url); }; diff --git a/Example/WebIDL-files/FormData.webidl b/Example/WebIDL-files/FormData.webidl index 73db65f..aa59a10 100644 --- a/Example/WebIDL-files/FormData.webidl +++ b/Example/WebIDL-files/FormData.webidl @@ -5,13 +5,13 @@ typedef (File or USVString) FormDataEntryValue; interface FormData { constructor(optional HTMLFormElement form); - void append(USVString name, USVString value); - void append(USVString name, Blob blobValue, optional USVString filename); - void delete(USVString name); + undefined append(USVString name, USVString value); + undefined append(USVString name, Blob blobValue, optional USVString filename); + undefined delete(USVString name); FormDataEntryValue? get(USVString name); sequence getAll(USVString name); boolean has(USVString name); - void set(USVString name, USVString value); - void set(USVString name, Blob blobValue, optional USVString filename); + undefined set(USVString name, USVString value); + undefined set(USVString name, Blob blobValue, optional USVString filename); iterable; }; diff --git a/Example/WebIDL-files/HTMLFormElement.webidl b/Example/WebIDL-files/HTMLFormElement.webidl index a596d07..ccdc635 100644 --- a/Example/WebIDL-files/HTMLFormElement.webidl +++ b/Example/WebIDL-files/HTMLFormElement.webidl @@ -22,9 +22,9 @@ interface HTMLFormElement : HTMLElement { getter Element (unsigned long index); getter (RadioNodeList or Element) (DOMString name); - void submit(); - void requestSubmit(optional HTMLElement? submitter = null); - [CEReactions] void reset(); + undefined submit(); + undefined requestSubmit(optional HTMLElement? submitter = null); + [CEReactions] undefined reset(); boolean checkValidity(); boolean reportValidity(); }; @@ -41,7 +41,7 @@ interface HTMLElement : Element { // user interaction [CEReactions] attribute boolean hidden; - void click(); + undefined click(); [CEReactions] attribute DOMString accessKey; readonly attribute DOMString accessKeyLabel; [CEReactions] attribute boolean draggable; @@ -76,12 +76,12 @@ interface RadioNodeList : NodeList { interface ElementInternals { // Form-associated custom elements - void setFormValue((File or USVString or FormData)? value, + undefined setFormValue((File or USVString or FormData)? value, optional (File or USVString or FormData)? state); readonly attribute HTMLFormElement? form; - void setValidity(ValidityStateFlags flags, + undefined setValidity(ValidityStateFlags flags, optional DOMString message, optional HTMLElement anchor); readonly attribute boolean willValidate; diff --git a/Example/WebIDL-files/HTMLOrSVGElement.webidl b/Example/WebIDL-files/HTMLOrSVGElement.webidl index ab03091..f511ad4 100644 --- a/Example/WebIDL-files/HTMLOrSVGElement.webidl +++ b/Example/WebIDL-files/HTMLOrSVGElement.webidl @@ -5,8 +5,8 @@ interface mixin HTMLOrSVGElement { [CEReactions] attribute boolean autofocus; [CEReactions] attribute long tabIndex; - void focus(optional FocusOptions options = {}); - void blur(); + undefined focus(optional FocusOptions options = {}); + undefined blur(); }; dictionary FocusOptions { diff --git a/Example/WebIDL-files/console.webidl b/Example/WebIDL-files/console.webidl index aea9474..6c9182c 100644 --- a/Example/WebIDL-files/console.webidl +++ b/Example/WebIDL-files/console.webidl @@ -1,29 +1,29 @@ [Exposed=(Window,Worker,Worklet)] namespace console { // but see namespace object requirements below // Logging - void assert(optional boolean condition = false, any... data); - void clear(); - void debug(any... data); - void error(any... data); - void info(any... data); - void log(any... data); - void table(optional any tabularData, optional sequence properties); - void trace(any... data); - void warn(any... data); - void dir(optional any item, optional object? options); - void dirxml(any... data); + undefined assert(optional boolean condition = false, any... data); + undefined clear(); + undefined debug(any... data); + undefined error(any... data); + undefined info(any... data); + undefined log(any... data); + undefined table(optional any tabularData, optional sequence properties); + undefined trace(any... data); + undefined warn(any... data); + undefined dir(optional any item, optional object? options); + undefined dirxml(any... data); // Counting - void count(optional DOMString label = "default"); - void countReset(optional DOMString label = "default"); + undefined count(optional DOMString label = "default"); + undefined countReset(optional DOMString label = "default"); // Grouping - void group(any... data); - void groupCollapsed(any... data); - void groupEnd(); + undefined group(any... data); + undefined groupCollapsed(any... data); + undefined groupEnd(); // Timing - void time(optional DOMString label = "default"); - void timeLog(optional DOMString label = "default", any... data); - void timeEnd(optional DOMString label = "default"); + undefined time(optional DOMString label = "default"); + undefined timeLog(optional DOMString label = "default", any... data); + undefined timeEnd(optional DOMString label = "default"); }; diff --git a/Example/WebIDL-files/dom.webidl b/Example/WebIDL-files/dom.webidl index 9f8adca..0e37763 100644 --- a/Example/WebIDL-files/dom.webidl +++ b/Example/WebIDL-files/dom.webidl @@ -14,21 +14,21 @@ interface Event { const unsigned short BUBBLING_PHASE = 3; readonly attribute unsigned short eventPhase; - void stopPropagation(); + undefined stopPropagation(); attribute boolean cancelBubble; // historical alias of .stopPropagation - void stopImmediatePropagation(); + undefined stopImmediatePropagation(); readonly attribute boolean bubbles; readonly attribute boolean cancelable; attribute boolean returnValue; // historical - void preventDefault(); + undefined preventDefault(); readonly attribute boolean defaultPrevented; readonly attribute boolean composed; [Unforgeable] readonly attribute boolean isTrusted; readonly attribute DOMHighResTimeStamp timeStamp; - void initEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false); // historical + undefined initEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false); // historical }; dictionary EventInit { @@ -47,7 +47,7 @@ interface CustomEvent : Event { readonly attribute any detail; - void initCustomEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any detail = null); // historical + undefined initCustomEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any detail = null); // historical }; dictionary CustomEventInit : EventInit { @@ -58,13 +58,13 @@ dictionary CustomEventInit : EventInit { interface EventTarget { constructor(); - void addEventListener(DOMString type, EventListener? callback, optional (AddEventListenerOptions or boolean) options = {}); - void removeEventListener(DOMString type, EventListener? callback, optional (EventListenerOptions or boolean) options = {}); + undefined addEventListener(DOMString type, EventListener? callback, optional (AddEventListenerOptions or boolean) options = {}); + undefined removeEventListener(DOMString type, EventListener? callback, optional (EventListenerOptions or boolean) options = {}); boolean dispatchEvent(Event event); }; callback interface EventListener { - void handleEvent(Event event); + undefined handleEvent(Event event); }; dictionary EventListenerOptions { @@ -82,7 +82,7 @@ interface AbortController { [SameObject] readonly attribute AbortSignal signal; - void abort(); + undefined abort(); }; [Exposed=(Window,Worker)] @@ -108,8 +108,8 @@ interface mixin ParentNode { readonly attribute Element? lastElementChild; readonly attribute unsigned long childElementCount; - [CEReactions, Unscopable] void prepend((Node or DOMString)... nodes); - [CEReactions, Unscopable] void append((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined prepend((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined append((Node or DOMString)... nodes); Element? querySelector(DOMString selectors); [NewObject] NodeList querySelectorAll(DOMString selectors); @@ -126,10 +126,10 @@ Element includes NonDocumentTypeChildNode; CharacterData includes NonDocumentTypeChildNode; interface mixin ChildNode { - [CEReactions, Unscopable] void before((Node or DOMString)... nodes); - [CEReactions, Unscopable] void after((Node or DOMString)... nodes); - [CEReactions, Unscopable] void replaceWith((Node or DOMString)... nodes); - [CEReactions, Unscopable] void remove(); + [CEReactions, Unscopable] undefined before((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined after((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined replaceWith((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined remove(); }; DocumentType includes ChildNode; Element includes ChildNode; @@ -159,12 +159,12 @@ interface HTMLCollection { interface MutationObserver { constructor(MutationCallback callback); - void observe(Node target, optional MutationObserverInit options = {}); - void disconnect(); + undefined observe(Node target, optional MutationObserverInit options = {}); + undefined disconnect(); sequence takeRecords(); }; -callback MutationCallback = void (sequence mutations, MutationObserver observer); +callback MutationCallback = undefined (sequence mutations, MutationObserver observer); dictionary MutationObserverInit { boolean childList = false; @@ -222,7 +222,7 @@ interface Node : EventTarget { [CEReactions] attribute DOMString? nodeValue; [CEReactions] attribute DOMString? textContent; - [CEReactions] void normalize(); + [CEReactions] undefined normalize(); [CEReactions, NewObject] Node cloneNode(optional boolean deep = false); boolean isEqualNode(Node? otherNode); @@ -347,10 +347,10 @@ interface Element : Node { sequence getAttributeNames(); DOMString? getAttribute(DOMString qualifiedName); DOMString? getAttributeNS(DOMString? namespace, DOMString localName); - [CEReactions] void setAttribute(DOMString qualifiedName, DOMString value); - [CEReactions] void setAttributeNS(DOMString? namespace, DOMString qualifiedName, DOMString value); - [CEReactions] void removeAttribute(DOMString qualifiedName); - [CEReactions] void removeAttributeNS(DOMString? namespace, DOMString localName); + [CEReactions] undefined setAttribute(DOMString qualifiedName, DOMString value); + [CEReactions] undefined setAttributeNS(DOMString? namespace, DOMString qualifiedName, DOMString value); + [CEReactions] undefined removeAttribute(DOMString qualifiedName); + [CEReactions] undefined removeAttributeNS(DOMString? namespace, DOMString localName); [CEReactions] boolean toggleAttribute(DOMString qualifiedName, optional boolean force); boolean hasAttribute(DOMString qualifiedName); boolean hasAttributeNS(DOMString? namespace, DOMString localName); @@ -373,7 +373,7 @@ interface Element : Node { HTMLCollection getElementsByClassName(DOMString classNames); [CEReactions] Element? insertAdjacentElement(DOMString where, Element element); // historical - void insertAdjacentText(DOMString where, DOMString data); // historical + undefined insertAdjacentText(DOMString where, DOMString data); // historical }; dictionary ShadowRootInit { @@ -411,10 +411,10 @@ interface CharacterData : Node { attribute [TreatNullAs=EmptyString] DOMString data; readonly attribute unsigned long length; DOMString substringData(unsigned long offset, unsigned long count); - void appendData(DOMString data); - void insertData(unsigned long offset, DOMString data); - void deleteData(unsigned long offset, unsigned long count); - void replaceData(unsigned long offset, unsigned long count, DOMString data); + undefined appendData(DOMString data); + undefined insertData(unsigned long offset, DOMString data); + undefined deleteData(unsigned long offset, unsigned long count); + undefined replaceData(unsigned long offset, unsigned long count, DOMString data); }; [Exposed=Window] @@ -464,15 +464,15 @@ interface Range : AbstractRange { readonly attribute Node commonAncestorContainer; - void setStart(Node node, unsigned long offset); - void setEnd(Node node, unsigned long offset); - void setStartBefore(Node node); - void setStartAfter(Node node); - void setEndBefore(Node node); - void setEndAfter(Node node); - void collapse(optional boolean toStart = false); - void selectNode(Node node); - void selectNodeContents(Node node); + undefined setStart(Node node, unsigned long offset); + undefined setEnd(Node node, unsigned long offset); + undefined setStartBefore(Node node); + undefined setStartAfter(Node node); + undefined setEndBefore(Node node); + undefined setEndAfter(Node node); + undefined collapse(optional boolean toStart = false); + undefined selectNode(Node node); + undefined selectNodeContents(Node node); const unsigned short START_TO_START = 0; const unsigned short START_TO_END = 1; @@ -480,14 +480,14 @@ interface Range : AbstractRange { const unsigned short END_TO_START = 3; short compareBoundaryPoints(unsigned short how, Range sourceRange); - [CEReactions] void deleteContents(); + [CEReactions] undefined deleteContents(); [CEReactions, NewObject] DocumentFragment extractContents(); [CEReactions, NewObject] DocumentFragment cloneContents(); - [CEReactions] void insertNode(Node node); - [CEReactions] void surroundContents(Node newParent); + [CEReactions] undefined insertNode(Node node); + [CEReactions] undefined surroundContents(Node newParent); [NewObject] Range cloneRange(); - void detach(); + undefined detach(); boolean isPointInRange(Node node, unsigned long offset); short comparePoint(Node node, unsigned long offset); @@ -508,7 +508,7 @@ interface NodeIterator { Node? nextNode(); Node? previousNode(); - void detach(); + undefined detach(); }; [Exposed=Window] @@ -556,8 +556,8 @@ interface DOMTokenList { readonly attribute unsigned long length; getter DOMString? item(unsigned long index); boolean contains(DOMString token); - [CEReactions] void add(DOMString... tokens); - [CEReactions] void remove(DOMString... tokens); + [CEReactions] undefined add(DOMString... tokens); + [CEReactions] undefined remove(DOMString... tokens); [CEReactions] boolean toggle(DOMString token, optional boolean force); [CEReactions] boolean replace(DOMString token, DOMString newToken); boolean supports(DOMString token); From 675e61f83835129ef0e32077ddd078d4537bd644 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Thu, 1 Oct 2020 10:48:09 -0400 Subject: [PATCH 20/22] Also update the other webidl files --- Tests/WebIDL-files/CommonDefinitions.webidl | 2 +- Tests/WebIDL-files/DOMStringMap.webidl | 4 +- Tests/WebIDL-files/Element_Scrolling.webidl | 40 ++++----- Tests/WebIDL-files/FileAPI.webidl | 12 +-- Tests/WebIDL-files/FormData.webidl | 10 +-- Tests/WebIDL-files/HTMLButtonElement.webidl | 4 +- Tests/WebIDL-files/HTMLFormElement.webidl | 12 +-- Tests/WebIDL-files/HTMLOrSVGElement.webidl | 4 +- Tests/WebIDL-files/HTMLTextAreaElement.webidl | 10 +-- Tests/WebIDL-files/MediaSource.webidl | 20 ++--- Tests/WebIDL-files/Performance.webidl | 6 +- Tests/WebIDL-files/URLSearchParams.webidl | 8 +- Tests/WebIDL-files/WebSocket.webidl | 24 ++--- .../WindowOrWorkerGlobalScope.webidl | 8 +- Tests/WebIDL-files/XMLHttpRequest.webidl | 12 +-- Tests/WebIDL-files/console.webidl | 38 ++++---- Tests/WebIDL-files/dom.webidl | 88 +++++++++---------- 17 files changed, 151 insertions(+), 151 deletions(-) diff --git a/Tests/WebIDL-files/CommonDefinitions.webidl b/Tests/WebIDL-files/CommonDefinitions.webidl index d1dabfa..eb78bc5 100644 --- a/Tests/WebIDL-files/CommonDefinitions.webidl +++ b/Tests/WebIDL-files/CommonDefinitions.webidl @@ -44,4 +44,4 @@ typedef unsigned long long DOMTimeStamp; callback Function = any (any... arguments); -callback VoidFunction = void (); +callback VoidFunction = undefined (); diff --git a/Tests/WebIDL-files/DOMStringMap.webidl b/Tests/WebIDL-files/DOMStringMap.webidl index 5b60130..d81a086 100644 --- a/Tests/WebIDL-files/DOMStringMap.webidl +++ b/Tests/WebIDL-files/DOMStringMap.webidl @@ -1,6 +1,6 @@ interface DOMStringMap { getter DOMString (DOMString name); - [CEReactions] setter void (DOMString name, DOMString value); - [CEReactions] deleter void (DOMString name); + [CEReactions] setter undefined (DOMString name, DOMString value); + [CEReactions] deleter undefined (DOMString name); }; diff --git a/Tests/WebIDL-files/Element_Scrolling.webidl b/Tests/WebIDL-files/Element_Scrolling.webidl index f036395..6eadf53 100644 --- a/Tests/WebIDL-files/Element_Scrolling.webidl +++ b/Tests/WebIDL-files/Element_Scrolling.webidl @@ -7,13 +7,13 @@ dictionary ScrollIntoViewOptions : ScrollOptions { partial interface Element { DOMRectList getClientRects(); [NewObject] DOMRect getBoundingClientRect(); - void scrollIntoView(optional (boolean or ScrollIntoViewOptions) arg = {}); - void scroll(optional ScrollToOptions options = {}); - void scroll(unrestricted double x, unrestricted double y); - void scrollTo(optional ScrollToOptions options = {}); - void scrollTo(unrestricted double x, unrestricted double y); - void scrollBy(optional ScrollToOptions options = {}); - void scrollBy(unrestricted double x, unrestricted double y); + undefined scrollIntoView(optional (boolean or ScrollIntoViewOptions) arg = {}); + undefined scroll(optional ScrollToOptions options = {}); + undefined scroll(unrestricted double x, unrestricted double y); + undefined scrollTo(optional ScrollToOptions options = {}); + undefined scrollTo(unrestricted double x, unrestricted double y); + undefined scrollBy(optional ScrollToOptions options = {}); + undefined scrollBy(unrestricted double x, unrestricted double y); attribute unrestricted double scrollTop; attribute unrestricted double scrollLeft; readonly attribute long scrollWidth; @@ -81,10 +81,10 @@ partial interface Window { [SameObject, Replaceable] readonly attribute Screen screen; // browsing context - void moveTo(long x, long y); - void moveBy(long x, long y); - void resizeTo(long width, long height); - void resizeBy(long x, long y); + undefined moveTo(long x, long y); + undefined moveBy(long x, long y); + undefined resizeTo(long width, long height); + undefined resizeBy(long x, long y); // viewport [Replaceable] readonly attribute long innerWidth; @@ -95,12 +95,12 @@ partial interface Window { [Replaceable] readonly attribute double pageXOffset; [Replaceable] readonly attribute double scrollY; [Replaceable] readonly attribute double pageYOffset; - void scroll(optional ScrollToOptions options = {}); - void scroll(unrestricted double x, unrestricted double y); - void scrollTo(optional ScrollToOptions options = {}); - void scrollTo(unrestricted double x, unrestricted double y); - void scrollBy(optional ScrollToOptions options = {}); - void scrollBy(unrestricted double x, unrestricted double y); + undefined scroll(optional ScrollToOptions options = {}); + undefined scroll(unrestricted double x, unrestricted double y); + undefined scrollTo(optional ScrollToOptions options = {}); + undefined scrollTo(unrestricted double x, unrestricted double y); + undefined scrollBy(optional ScrollToOptions options = {}); + undefined scrollBy(unrestricted double x, unrestricted double y); // client [Replaceable] readonly attribute long screenX; @@ -121,8 +121,8 @@ interface DOMRectList { interface MediaQueryList : EventTarget { readonly attribute CSSOMString media; readonly attribute boolean matches; - void addListener(EventListener? callback); - void removeListener(EventListener? callback); + undefined addListener(EventListener? callback); + undefined removeListener(EventListener? callback); attribute EventHandler onchange; }; @@ -136,4 +136,4 @@ interface Screen { readonly attribute long height; readonly attribute unsigned long colorDepth; readonly attribute unsigned long pixelDepth; -}; \ No newline at end of file +}; diff --git a/Tests/WebIDL-files/FileAPI.webidl b/Tests/WebIDL-files/FileAPI.webidl index c92c76e..b980a47 100644 --- a/Tests/WebIDL-files/FileAPI.webidl +++ b/Tests/WebIDL-files/FileAPI.webidl @@ -49,12 +49,12 @@ interface FileList { interface FileReader: EventTarget { constructor(); // async read methods - void readAsArrayBuffer(Blob blob); - void readAsBinaryString(Blob blob); - void readAsText(Blob blob, optional DOMString encoding); - void readAsDataURL(Blob blob); + undefined readAsArrayBuffer(Blob blob); + undefined readAsBinaryString(Blob blob); + undefined readAsText(Blob blob, optional DOMString encoding); + undefined readAsDataURL(Blob blob); - void abort(); + undefined abort(); // states const unsigned short EMPTY = 0; @@ -91,5 +91,5 @@ interface FileReaderSync { [Exposed=(Window,DedicatedWorker,SharedWorker)] partial interface URL { static DOMString createObjectURL((Blob or MediaSource) obj); - static void revokeObjectURL(DOMString url); + static undefined revokeObjectURL(DOMString url); }; diff --git a/Tests/WebIDL-files/FormData.webidl b/Tests/WebIDL-files/FormData.webidl index 73db65f..aa59a10 100644 --- a/Tests/WebIDL-files/FormData.webidl +++ b/Tests/WebIDL-files/FormData.webidl @@ -5,13 +5,13 @@ typedef (File or USVString) FormDataEntryValue; interface FormData { constructor(optional HTMLFormElement form); - void append(USVString name, USVString value); - void append(USVString name, Blob blobValue, optional USVString filename); - void delete(USVString name); + undefined append(USVString name, USVString value); + undefined append(USVString name, Blob blobValue, optional USVString filename); + undefined delete(USVString name); FormDataEntryValue? get(USVString name); sequence getAll(USVString name); boolean has(USVString name); - void set(USVString name, USVString value); - void set(USVString name, Blob blobValue, optional USVString filename); + undefined set(USVString name, USVString value); + undefined set(USVString name, Blob blobValue, optional USVString filename); iterable; }; diff --git a/Tests/WebIDL-files/HTMLButtonElement.webidl b/Tests/WebIDL-files/HTMLButtonElement.webidl index 3cffc7d..12fc6ff 100644 --- a/Tests/WebIDL-files/HTMLButtonElement.webidl +++ b/Tests/WebIDL-files/HTMLButtonElement.webidl @@ -18,7 +18,7 @@ interface HTMLButtonElement : HTMLElement { readonly attribute DOMString validationMessage; boolean checkValidity(); boolean reportValidity(); - void setCustomValidity(DOMString error); + undefined setCustomValidity(DOMString error); readonly attribute NodeList labels; -}; \ No newline at end of file +}; diff --git a/Tests/WebIDL-files/HTMLFormElement.webidl b/Tests/WebIDL-files/HTMLFormElement.webidl index a596d07..ccdc635 100644 --- a/Tests/WebIDL-files/HTMLFormElement.webidl +++ b/Tests/WebIDL-files/HTMLFormElement.webidl @@ -22,9 +22,9 @@ interface HTMLFormElement : HTMLElement { getter Element (unsigned long index); getter (RadioNodeList or Element) (DOMString name); - void submit(); - void requestSubmit(optional HTMLElement? submitter = null); - [CEReactions] void reset(); + undefined submit(); + undefined requestSubmit(optional HTMLElement? submitter = null); + [CEReactions] undefined reset(); boolean checkValidity(); boolean reportValidity(); }; @@ -41,7 +41,7 @@ interface HTMLElement : Element { // user interaction [CEReactions] attribute boolean hidden; - void click(); + undefined click(); [CEReactions] attribute DOMString accessKey; readonly attribute DOMString accessKeyLabel; [CEReactions] attribute boolean draggable; @@ -76,12 +76,12 @@ interface RadioNodeList : NodeList { interface ElementInternals { // Form-associated custom elements - void setFormValue((File or USVString or FormData)? value, + undefined setFormValue((File or USVString or FormData)? value, optional (File or USVString or FormData)? state); readonly attribute HTMLFormElement? form; - void setValidity(ValidityStateFlags flags, + undefined setValidity(ValidityStateFlags flags, optional DOMString message, optional HTMLElement anchor); readonly attribute boolean willValidate; diff --git a/Tests/WebIDL-files/HTMLOrSVGElement.webidl b/Tests/WebIDL-files/HTMLOrSVGElement.webidl index ab03091..f511ad4 100644 --- a/Tests/WebIDL-files/HTMLOrSVGElement.webidl +++ b/Tests/WebIDL-files/HTMLOrSVGElement.webidl @@ -5,8 +5,8 @@ interface mixin HTMLOrSVGElement { [CEReactions] attribute boolean autofocus; [CEReactions] attribute long tabIndex; - void focus(optional FocusOptions options = {}); - void blur(); + undefined focus(optional FocusOptions options = {}); + undefined blur(); }; dictionary FocusOptions { diff --git a/Tests/WebIDL-files/HTMLTextAreaElement.webidl b/Tests/WebIDL-files/HTMLTextAreaElement.webidl index 3f9a986..7629b8f 100644 --- a/Tests/WebIDL-files/HTMLTextAreaElement.webidl +++ b/Tests/WebIDL-files/HTMLTextAreaElement.webidl @@ -27,17 +27,17 @@ interface HTMLTextAreaElement : HTMLElement { readonly attribute DOMString validationMessage; boolean checkValidity(); boolean reportValidity(); - void setCustomValidity(DOMString error); + undefined setCustomValidity(DOMString error); readonly attribute NodeList labels; - void select(); + undefined select(); attribute unsigned long selectionStart; attribute unsigned long selectionEnd; attribute DOMString selectionDirection; - void setRangeText(DOMString replacement); - void setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve"); - void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction); + undefined setRangeText(DOMString replacement); + undefined setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve"); + undefined setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction); }; enum SelectionMode { diff --git a/Tests/WebIDL-files/MediaSource.webidl b/Tests/WebIDL-files/MediaSource.webidl index 6df51f9..e4fa25e 100644 --- a/Tests/WebIDL-files/MediaSource.webidl +++ b/Tests/WebIDL-files/MediaSource.webidl @@ -9,10 +9,10 @@ interface MediaSource : EventTarget { attribute EventHandler onsourceended; attribute EventHandler onsourceclose; SourceBuffer addSourceBuffer (DOMString type); - void removeSourceBuffer (SourceBuffer sourceBuffer); - void endOfStream (optional EndOfStreamError error); - void setLiveSeekableRange (double start, double end); - void clearLiveSeekableRange (); + undefined removeSourceBuffer (SourceBuffer sourceBuffer); + undefined endOfStream (optional EndOfStreamError error); + undefined setLiveSeekableRange (double start, double end); + undefined clearLiveSeekableRange (); static boolean isTypeSupported (DOMString type); }; @@ -51,9 +51,9 @@ interface SourceBuffer : EventTarget { attribute EventHandler onupdateend; attribute EventHandler onerror; attribute EventHandler onabort; - void appendBuffer (BufferSource data); - void abort (); - void remove (double start, unrestricted double end); + undefined appendBuffer (BufferSource data); + undefined abort (); + undefined remove (double start, unrestricted double end); }; [Exposed=Window] @@ -135,8 +135,8 @@ interface TextTrack : EventTarget { readonly attribute TextTrackCueList? cues; readonly attribute TextTrackCueList? activeCues; - void addCue(TextTrackCue cue); - void removeCue(TextTrackCue cue); + undefined addCue(TextTrackCue cue); + undefined removeCue(TextTrackCue cue); attribute EventHandler oncuechange; }; @@ -159,4 +159,4 @@ interface TextTrackCueList { readonly attribute unsigned long length; getter TextTrackCue (unsigned long index); TextTrackCue? getCueById(DOMString id); -}; \ No newline at end of file +}; diff --git a/Tests/WebIDL-files/Performance.webidl b/Tests/WebIDL-files/Performance.webidl index e566e1f..6481564 100644 --- a/Tests/WebIDL-files/Performance.webidl +++ b/Tests/WebIDL-files/Performance.webidl @@ -32,9 +32,9 @@ dictionary PerformanceMeasureOptions { partial interface Performance { PerformanceMark mark(DOMString markName, optional PerformanceMarkOptions markOptions = {}); - void clearMarks(optional DOMString markName); + undefined clearMarks(optional DOMString markName); PerformanceMeasure measure(DOMString measureName, optional (DOMString or PerformanceMeasureOptions) startOrMeasureOptions = {}, optional DOMString endMark); - void clearMeasures(optional DOMString measureName); + undefined clearMeasures(optional DOMString measureName); }; [Exposed=(Window,Worker)] @@ -55,4 +55,4 @@ interface PerformanceEntry { interface PerformanceMark : PerformanceEntry { constructor(DOMString markName, optional PerformanceMarkOptions markOptions = {}); readonly attribute any detail; -}; \ No newline at end of file +}; diff --git a/Tests/WebIDL-files/URLSearchParams.webidl b/Tests/WebIDL-files/URLSearchParams.webidl index 20d578f..760fb26 100644 --- a/Tests/WebIDL-files/URLSearchParams.webidl +++ b/Tests/WebIDL-files/URLSearchParams.webidl @@ -3,14 +3,14 @@ interface URLSearchParams { constructor(optional (sequence> or record or USVString) init = ""); - void append(USVString name, USVString value); - void delete(USVString name); + undefined append(USVString name, USVString value); + undefined delete(USVString name); USVString? get(USVString name); sequence getAll(USVString name); boolean has(USVString name); - void set(USVString name, USVString value); + undefined set(USVString name, USVString value); - void sort(); + undefined sort(); iterable; stringifier; diff --git a/Tests/WebIDL-files/WebSocket.webidl b/Tests/WebIDL-files/WebSocket.webidl index 91432dc..d0daaa1 100644 --- a/Tests/WebIDL-files/WebSocket.webidl +++ b/Tests/WebIDL-files/WebSocket.webidl @@ -24,15 +24,15 @@ interface WebSocket : EventTarget { attribute EventHandler onclose; //readonly attribute DOMString extensions; readonly attribute DOMString protocol; - [Throws] void close(optional [Clamp] unsigned short code, optional USVString reason); + [Throws] undefined close(optional [Clamp] unsigned short code, optional USVString reason); //messaging attribute EventHandler onmessage; attribute BinaryType binaryType; - [Throws] void send(USVString data); - [Throws] void send(Blob data); - [Throws] void send(ArrayBuffer data); - [Throws] void send(ArrayBufferView data); + [Throws] undefined send(USVString data); + [Throws] undefined send(Blob data); + [Throws] undefined send(ArrayBuffer data); + [Throws] undefined send(ArrayBufferView data); }; interface MessageEvent : Event { @@ -44,7 +44,7 @@ interface MessageEvent : Event { readonly attribute MessageEventSource? source; readonly attribute FrozenArray ports; - void initMessageEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any data = null, optional USVString origin = "", optional DOMString lastEventId = "", optional MessageEventSource? source = null, optional sequence ports = []); + undefined initMessageEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any data = null, optional USVString origin = "", optional DOMString lastEventId = "", optional MessageEventSource? source = null, optional sequence ports = []); }; dictionary MessageEventInit : EventInit { @@ -60,10 +60,10 @@ typedef (MessagePort or ServiceWorker) MessageEventSource; [Exposed=(Window,Worker,AudioWorklet), Transferable] interface MessagePort : EventTarget { - void postMessage(any message, sequence transfer); - void postMessage(any message, optional PostMessageOptions options = {}); - void start(); - void close(); + undefined postMessage(any message, sequence transfer); + undefined postMessage(any message, optional PostMessageOptions options = {}); + undefined start(); + undefined close(); // event handlers attribute EventHandler onmessage; @@ -77,8 +77,8 @@ dictionary PostMessageOptions { interface ServiceWorker : EventTarget { readonly attribute USVString scriptURL; readonly attribute ServiceWorkerState state; - void postMessage(any message, sequence transfer); - void postMessage(any message, optional PostMessageOptions options = {}); + undefined postMessage(any message, sequence transfer); + undefined postMessage(any message, optional PostMessageOptions options = {}); // event attribute EventHandler onstatechange; diff --git a/Tests/WebIDL-files/WindowOrWorkerGlobalScope.webidl b/Tests/WebIDL-files/WindowOrWorkerGlobalScope.webidl index 6c3b26e..6d67956 100644 --- a/Tests/WebIDL-files/WindowOrWorkerGlobalScope.webidl +++ b/Tests/WebIDL-files/WindowOrWorkerGlobalScope.webidl @@ -9,16 +9,16 @@ interface mixin WindowOrWorkerGlobalScope { // timers // long setTimeout(TimerHandler handler, optional long timeout = 0, any... arguments); - // void clearTimeout(optional long handle = 0); + // undefined clearTimeout(optional long handle = 0); // long setInterval(TimerHandler handler, optional long timeout = 0, any... arguments); - // void clearInterval(optional long handle = 0); + // undefined clearInterval(optional long handle = 0); // microtask queuing - // void queueMicrotask(VoidFunction callback); + // undefined queueMicrotask(VoidFunction callback); // ImageBitmap // Promise createImageBitmap(ImageBitmapSource image, optional ImageBitmapOptions options = {}); // Promise createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh, optional ImageBitmapOptions options = {}); }; Window includes WindowOrWorkerGlobalScope; -WorkerGlobalScope includes WindowOrWorkerGlobalScope; \ No newline at end of file +WorkerGlobalScope includes WindowOrWorkerGlobalScope; diff --git a/Tests/WebIDL-files/XMLHttpRequest.webidl b/Tests/WebIDL-files/XMLHttpRequest.webidl index 6c65651..17fa8c8 100644 --- a/Tests/WebIDL-files/XMLHttpRequest.webidl +++ b/Tests/WebIDL-files/XMLHttpRequest.webidl @@ -56,14 +56,14 @@ interface XMLHttpRequest : XMLHttpRequestEventTarget { readonly attribute unsigned short readyState; // request - void open(ByteString method, USVString url); - void open(ByteString method, USVString url, boolean async, optional USVString? username = null, optional USVString? password = null); - void setRequestHeader(ByteString name, ByteString value); + undefined open(ByteString method, USVString url); + undefined open(ByteString method, USVString url, boolean async, optional USVString? username = null, optional USVString? password = null); + undefined setRequestHeader(ByteString name, ByteString value); attribute unsigned long timeout; attribute boolean withCredentials; [SameObject] readonly attribute XMLHttpRequestUpload upload; - void send(optional (Document or BodyInit)? body = null); - void abort(); + undefined send(optional (Document or BodyInit)? body = null); + undefined abort(); // response readonly attribute USVString responseURL; @@ -71,7 +71,7 @@ interface XMLHttpRequest : XMLHttpRequestEventTarget { readonly attribute ByteString statusText; ByteString? getResponseHeader(ByteString name); ByteString getAllResponseHeaders(); - void overrideMimeType(DOMString mime); + undefined overrideMimeType(DOMString mime); attribute XMLHttpRequestResponseType responseType; readonly attribute any response; readonly attribute USVString responseText; diff --git a/Tests/WebIDL-files/console.webidl b/Tests/WebIDL-files/console.webidl index aea9474..6c9182c 100644 --- a/Tests/WebIDL-files/console.webidl +++ b/Tests/WebIDL-files/console.webidl @@ -1,29 +1,29 @@ [Exposed=(Window,Worker,Worklet)] namespace console { // but see namespace object requirements below // Logging - void assert(optional boolean condition = false, any... data); - void clear(); - void debug(any... data); - void error(any... data); - void info(any... data); - void log(any... data); - void table(optional any tabularData, optional sequence properties); - void trace(any... data); - void warn(any... data); - void dir(optional any item, optional object? options); - void dirxml(any... data); + undefined assert(optional boolean condition = false, any... data); + undefined clear(); + undefined debug(any... data); + undefined error(any... data); + undefined info(any... data); + undefined log(any... data); + undefined table(optional any tabularData, optional sequence properties); + undefined trace(any... data); + undefined warn(any... data); + undefined dir(optional any item, optional object? options); + undefined dirxml(any... data); // Counting - void count(optional DOMString label = "default"); - void countReset(optional DOMString label = "default"); + undefined count(optional DOMString label = "default"); + undefined countReset(optional DOMString label = "default"); // Grouping - void group(any... data); - void groupCollapsed(any... data); - void groupEnd(); + undefined group(any... data); + undefined groupCollapsed(any... data); + undefined groupEnd(); // Timing - void time(optional DOMString label = "default"); - void timeLog(optional DOMString label = "default", any... data); - void timeEnd(optional DOMString label = "default"); + undefined time(optional DOMString label = "default"); + undefined timeLog(optional DOMString label = "default", any... data); + undefined timeEnd(optional DOMString label = "default"); }; diff --git a/Tests/WebIDL-files/dom.webidl b/Tests/WebIDL-files/dom.webidl index 9f8adca..0e37763 100644 --- a/Tests/WebIDL-files/dom.webidl +++ b/Tests/WebIDL-files/dom.webidl @@ -14,21 +14,21 @@ interface Event { const unsigned short BUBBLING_PHASE = 3; readonly attribute unsigned short eventPhase; - void stopPropagation(); + undefined stopPropagation(); attribute boolean cancelBubble; // historical alias of .stopPropagation - void stopImmediatePropagation(); + undefined stopImmediatePropagation(); readonly attribute boolean bubbles; readonly attribute boolean cancelable; attribute boolean returnValue; // historical - void preventDefault(); + undefined preventDefault(); readonly attribute boolean defaultPrevented; readonly attribute boolean composed; [Unforgeable] readonly attribute boolean isTrusted; readonly attribute DOMHighResTimeStamp timeStamp; - void initEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false); // historical + undefined initEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false); // historical }; dictionary EventInit { @@ -47,7 +47,7 @@ interface CustomEvent : Event { readonly attribute any detail; - void initCustomEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any detail = null); // historical + undefined initCustomEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any detail = null); // historical }; dictionary CustomEventInit : EventInit { @@ -58,13 +58,13 @@ dictionary CustomEventInit : EventInit { interface EventTarget { constructor(); - void addEventListener(DOMString type, EventListener? callback, optional (AddEventListenerOptions or boolean) options = {}); - void removeEventListener(DOMString type, EventListener? callback, optional (EventListenerOptions or boolean) options = {}); + undefined addEventListener(DOMString type, EventListener? callback, optional (AddEventListenerOptions or boolean) options = {}); + undefined removeEventListener(DOMString type, EventListener? callback, optional (EventListenerOptions or boolean) options = {}); boolean dispatchEvent(Event event); }; callback interface EventListener { - void handleEvent(Event event); + undefined handleEvent(Event event); }; dictionary EventListenerOptions { @@ -82,7 +82,7 @@ interface AbortController { [SameObject] readonly attribute AbortSignal signal; - void abort(); + undefined abort(); }; [Exposed=(Window,Worker)] @@ -108,8 +108,8 @@ interface mixin ParentNode { readonly attribute Element? lastElementChild; readonly attribute unsigned long childElementCount; - [CEReactions, Unscopable] void prepend((Node or DOMString)... nodes); - [CEReactions, Unscopable] void append((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined prepend((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined append((Node or DOMString)... nodes); Element? querySelector(DOMString selectors); [NewObject] NodeList querySelectorAll(DOMString selectors); @@ -126,10 +126,10 @@ Element includes NonDocumentTypeChildNode; CharacterData includes NonDocumentTypeChildNode; interface mixin ChildNode { - [CEReactions, Unscopable] void before((Node or DOMString)... nodes); - [CEReactions, Unscopable] void after((Node or DOMString)... nodes); - [CEReactions, Unscopable] void replaceWith((Node or DOMString)... nodes); - [CEReactions, Unscopable] void remove(); + [CEReactions, Unscopable] undefined before((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined after((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined replaceWith((Node or DOMString)... nodes); + [CEReactions, Unscopable] undefined remove(); }; DocumentType includes ChildNode; Element includes ChildNode; @@ -159,12 +159,12 @@ interface HTMLCollection { interface MutationObserver { constructor(MutationCallback callback); - void observe(Node target, optional MutationObserverInit options = {}); - void disconnect(); + undefined observe(Node target, optional MutationObserverInit options = {}); + undefined disconnect(); sequence takeRecords(); }; -callback MutationCallback = void (sequence mutations, MutationObserver observer); +callback MutationCallback = undefined (sequence mutations, MutationObserver observer); dictionary MutationObserverInit { boolean childList = false; @@ -222,7 +222,7 @@ interface Node : EventTarget { [CEReactions] attribute DOMString? nodeValue; [CEReactions] attribute DOMString? textContent; - [CEReactions] void normalize(); + [CEReactions] undefined normalize(); [CEReactions, NewObject] Node cloneNode(optional boolean deep = false); boolean isEqualNode(Node? otherNode); @@ -347,10 +347,10 @@ interface Element : Node { sequence getAttributeNames(); DOMString? getAttribute(DOMString qualifiedName); DOMString? getAttributeNS(DOMString? namespace, DOMString localName); - [CEReactions] void setAttribute(DOMString qualifiedName, DOMString value); - [CEReactions] void setAttributeNS(DOMString? namespace, DOMString qualifiedName, DOMString value); - [CEReactions] void removeAttribute(DOMString qualifiedName); - [CEReactions] void removeAttributeNS(DOMString? namespace, DOMString localName); + [CEReactions] undefined setAttribute(DOMString qualifiedName, DOMString value); + [CEReactions] undefined setAttributeNS(DOMString? namespace, DOMString qualifiedName, DOMString value); + [CEReactions] undefined removeAttribute(DOMString qualifiedName); + [CEReactions] undefined removeAttributeNS(DOMString? namespace, DOMString localName); [CEReactions] boolean toggleAttribute(DOMString qualifiedName, optional boolean force); boolean hasAttribute(DOMString qualifiedName); boolean hasAttributeNS(DOMString? namespace, DOMString localName); @@ -373,7 +373,7 @@ interface Element : Node { HTMLCollection getElementsByClassName(DOMString classNames); [CEReactions] Element? insertAdjacentElement(DOMString where, Element element); // historical - void insertAdjacentText(DOMString where, DOMString data); // historical + undefined insertAdjacentText(DOMString where, DOMString data); // historical }; dictionary ShadowRootInit { @@ -411,10 +411,10 @@ interface CharacterData : Node { attribute [TreatNullAs=EmptyString] DOMString data; readonly attribute unsigned long length; DOMString substringData(unsigned long offset, unsigned long count); - void appendData(DOMString data); - void insertData(unsigned long offset, DOMString data); - void deleteData(unsigned long offset, unsigned long count); - void replaceData(unsigned long offset, unsigned long count, DOMString data); + undefined appendData(DOMString data); + undefined insertData(unsigned long offset, DOMString data); + undefined deleteData(unsigned long offset, unsigned long count); + undefined replaceData(unsigned long offset, unsigned long count, DOMString data); }; [Exposed=Window] @@ -464,15 +464,15 @@ interface Range : AbstractRange { readonly attribute Node commonAncestorContainer; - void setStart(Node node, unsigned long offset); - void setEnd(Node node, unsigned long offset); - void setStartBefore(Node node); - void setStartAfter(Node node); - void setEndBefore(Node node); - void setEndAfter(Node node); - void collapse(optional boolean toStart = false); - void selectNode(Node node); - void selectNodeContents(Node node); + undefined setStart(Node node, unsigned long offset); + undefined setEnd(Node node, unsigned long offset); + undefined setStartBefore(Node node); + undefined setStartAfter(Node node); + undefined setEndBefore(Node node); + undefined setEndAfter(Node node); + undefined collapse(optional boolean toStart = false); + undefined selectNode(Node node); + undefined selectNodeContents(Node node); const unsigned short START_TO_START = 0; const unsigned short START_TO_END = 1; @@ -480,14 +480,14 @@ interface Range : AbstractRange { const unsigned short END_TO_START = 3; short compareBoundaryPoints(unsigned short how, Range sourceRange); - [CEReactions] void deleteContents(); + [CEReactions] undefined deleteContents(); [CEReactions, NewObject] DocumentFragment extractContents(); [CEReactions, NewObject] DocumentFragment cloneContents(); - [CEReactions] void insertNode(Node node); - [CEReactions] void surroundContents(Node newParent); + [CEReactions] undefined insertNode(Node node); + [CEReactions] undefined surroundContents(Node newParent); [NewObject] Range cloneRange(); - void detach(); + undefined detach(); boolean isPointInRange(Node node, unsigned long offset); short comparePoint(Node node, unsigned long offset); @@ -508,7 +508,7 @@ interface NodeIterator { Node? nextNode(); Node? previousNode(); - void detach(); + undefined detach(); }; [Exposed=Window] @@ -556,8 +556,8 @@ interface DOMTokenList { readonly attribute unsigned long length; getter DOMString? item(unsigned long index); boolean contains(DOMString token); - [CEReactions] void add(DOMString... tokens); - [CEReactions] void remove(DOMString... tokens); + [CEReactions] undefined add(DOMString... tokens); + [CEReactions] undefined remove(DOMString... tokens); [CEReactions] boolean toggle(DOMString token, optional boolean force); [CEReactions] boolean replace(DOMString token, DOMString newToken); boolean supports(DOMString token); From 15e0d573542425a52d76cc76171c1a975421a879 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Thu, 1 Oct 2020 11:21:07 -0400 Subject: [PATCH 21/22] Re-add void support --- .../IRGenerator.swift | 1 - Sources/WebIDL/Parser/Parser.swift | 7 ++-- Sources/WebIDL/Tokenizer/Terminal.swift | 1 + Tests/WebIDL-files/console.webidl | 38 +++++++++---------- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift index bb6c1eb..5778f4c 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IRGenerator.swift @@ -196,7 +196,6 @@ public class IRGenerator { .readWriteMaplike, .readWriteSetlike: fatalError("Member type \(member) not yet implemented") - return nil } } diff --git a/Sources/WebIDL/Parser/Parser.swift b/Sources/WebIDL/Parser/Parser.swift index 858978a..b0e007b 100644 --- a/Sources/WebIDL/Parser/Parser.swift +++ b/Sources/WebIDL/Parser/Parser.swift @@ -1635,7 +1635,8 @@ public class Parser { SingleType :: DistinguishableType any - undefinedå + undefined + void [removed from most recent spec] PromiseType */ @@ -1648,7 +1649,7 @@ public class Parser { tokens.removeFirst() return .any - case .terminal(.undefined): + case .terminal(.undefined), .terminal(.void): tokens.removeFirst() return .undefined @@ -2444,7 +2445,7 @@ func firstSet(for symbol: NonTerminal) -> Set { case .SingleType: return union( firstSet(for: .DistinguishableType), - [.terminal(.any), .terminal(.undefined)], + [.terminal(.any), .terminal(.undefined), .terminal(.void)], firstSet(for: .PromiseType) ) diff --git a/Sources/WebIDL/Tokenizer/Terminal.swift b/Sources/WebIDL/Tokenizer/Terminal.swift index 6e082e5..32391ce 100644 --- a/Sources/WebIDL/Tokenizer/Terminal.swift +++ b/Sources/WebIDL/Tokenizer/Terminal.swift @@ -82,6 +82,7 @@ public enum Terminal: String, Equatable, CustomStringConvertible { case unsigned = "unsigned" case short = "short" case long = "long" + case void = "void" // deprecated case undefined = "undefined" case ArrayBuffer = "ArrayBuffer" diff --git a/Tests/WebIDL-files/console.webidl b/Tests/WebIDL-files/console.webidl index 6c9182c..aea9474 100644 --- a/Tests/WebIDL-files/console.webidl +++ b/Tests/WebIDL-files/console.webidl @@ -1,29 +1,29 @@ [Exposed=(Window,Worker,Worklet)] namespace console { // but see namespace object requirements below // Logging - undefined assert(optional boolean condition = false, any... data); - undefined clear(); - undefined debug(any... data); - undefined error(any... data); - undefined info(any... data); - undefined log(any... data); - undefined table(optional any tabularData, optional sequence properties); - undefined trace(any... data); - undefined warn(any... data); - undefined dir(optional any item, optional object? options); - undefined dirxml(any... data); + void assert(optional boolean condition = false, any... data); + void clear(); + void debug(any... data); + void error(any... data); + void info(any... data); + void log(any... data); + void table(optional any tabularData, optional sequence properties); + void trace(any... data); + void warn(any... data); + void dir(optional any item, optional object? options); + void dirxml(any... data); // Counting - undefined count(optional DOMString label = "default"); - undefined countReset(optional DOMString label = "default"); + void count(optional DOMString label = "default"); + void countReset(optional DOMString label = "default"); // Grouping - undefined group(any... data); - undefined groupCollapsed(any... data); - undefined groupEnd(); + void group(any... data); + void groupCollapsed(any... data); + void groupEnd(); // Timing - undefined time(optional DOMString label = "default"); - undefined timeLog(optional DOMString label = "default", any... data); - undefined timeEnd(optional DOMString label = "default"); + void time(optional DOMString label = "default"); + void timeLog(optional DOMString label = "default", any... data); + void timeEnd(optional DOMString label = "default"); }; From a14fa2f9ab0cbac6e20bcdb1493a5338244dce72 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Thu, 1 Oct 2020 11:21:30 -0400 Subject: [PATCH 22/22] Update Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift Co-authored-by: Max Desiatov --- .../IntermediateRepresentation/Member Nodes/MethodNode.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift index 86e065d..1d36cfd 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift @@ -48,7 +48,9 @@ class MethodNode: MemberNode, Equatable { var params = params guard let idx = params.firstIndex(where: { $0.label == parameter.label }) else { continue } let param = params[idx] - guard let method = unwrapped.requiredMembers.first(where: { $0.isMethod && !$0.isStatic && !$0.isSubscript }) as? MethodNode else { continue } + guard let method = unwrapped.requiredMembers.first( + where: { $0.isMethod && !$0.isStatic && !$0.isSubscript } + ) as? MethodNode else { continue } let closureNode = ClosureNode(arguments: method.parameters.map { $0.dataType }, returnType: method.returnType) let typeNode: TypeNode