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); diff --git a/Sources/Commands/GenerateCode.swift b/Sources/Commands/GenerateCode.swift index 0515ebb..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) } @@ -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..5778f4c 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,18 +126,18 @@ 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) } } - ir.registerProtocol(withTypeName: mixin.identifier, inheritsFrom: [], requiredMembers: [], defaultImplementations: members) + ir.registerProtocol(withTypeName: mixin.identifier, inheritsFrom: [], requiredMembers: [], defaultImplementations: members, kind: .mixin) } func handleEnum(_ enumeration: Enum) { @@ -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) } } @@ -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, _): @@ -195,8 +195,7 @@ public class IRGenerator { case .asyncIterable, .readWriteMaplike, .readWriteSetlike: - // Not implemented yet. - return nil + fatalError("Member type \(member) not yet implemented") } } @@ -222,12 +221,12 @@ 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) { - let dataType = handleDataType(typedef.dataType) + let dataType = handleType(typedef.type) _ = ir.registerAliasNode(withTypeName: typedef.identifier, aliasing: unwrapNode(dataType)) } @@ -262,9 +261,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 +281,14 @@ public class IRGenerator { switch singleType { case .distinguishableType(let distinguishableType): return handleDistinguishableType(distinguishableType) + case .any: - return ir.registerBasicType(withTypeName: "AnyJSValueCodable") + 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 +337,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 { @@ -344,7 +346,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) } @@ -378,7 +380,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 +397,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 +430,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 +499,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 +520,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 +529,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 +548,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 +567,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 +622,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 +653,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 +666,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/IntermediateRepresentation/IntermediateRepresentation.swift b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift index 6bb4ccd..e15749d 100644 --- a/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift +++ b/Sources/WebIDL/IntermediateRepresentation/IntermediateRepresentation.swift @@ -240,7 +240,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: ProtocolNode.Kind) -> NodePointer { let nodePointer = existingOrNewNodePointer(for: typeName) let typeErasedPointer = existingOrNewNodePointer(for: "Any\(typeName)") @@ -252,7 +252,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) } @@ -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) diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ConstructorNode.swift index f10130a..db48117 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(unsafelyWrapping: \(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 b96cd13..1d36cfd 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/MethodNode.swift @@ -21,15 +21,74 @@ class MethodNode: MemberNode, Equatable { } // 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 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] + 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: typeNode + ), + 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 +118,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 +166,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 = 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 = "; return .undefined" + returnValue = "" } else { - returnValue = ".fromJSValue()" + returnValue = ".jsValue()" } 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) })" + let closureCode = "JSClosure { \($0.label)\(closureOptional ? "!" : "")(\(closureArguments))\(returnValue) }" + if closureOptional { + return "\($0.label) == nil ? nil : \(closureCode)" + } else { + return closureCode + } } else { return $0.label + ".jsValue()" } @@ -134,31 +209,26 @@ 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()! } """ } } 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 } diff --git a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/ReadWritePropertyNode.swift index c9ab1f5..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 @@ -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) + @OptionalClosureHandler(jsObject: Self.constructor, name: "\(name)") + 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) + @ClosureHandler(jsObject: Self.constructor, name: "\(name)") + 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 jsObject.\(escaped) } set { - objectRef[dynamicMember: "\(name)"] = newValue + jsObject.\(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 jsObject.\(escaped) } set { - objectRef[dynamicMember: "\(name)"] = newValue + jsObject\(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) + @ReadWriteAttribute(jsObject: Self.constructor, name: "\(name)") + 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 jsObject.\(escaped).fromJSValue()! as \(dataTypeNode.typeErasedSwiftType) } set { - objectRef.\(name) = newValue.jsValue() + jsObject.\(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 = jsObject.\(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 + jsObject.\(escaped) = JSClosure { arguments in return newValue(\(setterArguments)).jsValue() - }).jsValue() + }.jsValue() } else { - objectRef[dynamicMember: "\(name)"] = .null + jsObject.\(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 = jsObject.\(escaped).function! + return { (\(getterArguments)) in function(\(getterArguments)).fromJSValue()! } } set { - objectRef[dynamicMember: "\(name)"] = JSFunctionRef.from({ arguments in + jsObject.\(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 jsObject.\(escaped).fromJSValue()! } set { - objectRef.\(name) = 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 8ea115d..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 ae91871..3b7efea 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Member Nodes/SubscriptNode.swift @@ -70,21 +70,21 @@ class SubscriptNode: MemberNode, Equatable { let lookup: String declaration += " {\n" if isNamed { - lookup = "objectRef[dynamicMember: \(nameParameter.label)]" + lookup = "jsObject.\(escapedName(nameParameter.label))" } else { - lookup = "objectRef[\(nameParameter.label)]" + lookup = "jsObject[\(nameParameter.label)]" } 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..bedf918 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ClassNode.swift @@ -60,20 +60,20 @@ 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 { 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(objectRef: JSObjectRef) { + public required init(unsafelyWrapping 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(objectRef: JSObjectRef) { + public required init(unsafelyWrapping jsObject: JSObject) { \(propertyNodes.compactMap { $0.initializationStatement(forContext: context) }.joined(separator: "\n")) - super.init(objectRef: objectRef) + super.init(unsafelyWrapping: jsObject) } """ diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift index 6142dd8..43799dd 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/DictionaryNode.swift @@ -61,38 +61,36 @@ 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 { case \(cases.map(escapedName).joined(separator: ", ")) } - public typealias Value = AnyJSValueCodable - - private let dictionary: [String : AnyJSValueCodable] + private let dictionary: [String : JSValue] - 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(jsValue: JSValue) { - - self.dictionary = jsValue.fromJSValue() + public init?(from value: JSValue) { + if let dictionary: [String : JSValue] = value.fromJSValue() { + self.dictionary = dictionary + } + return nil } + 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 6cb9a33..995047e 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 decoded: \(typeName) = value.fromJSValue() { + self = .\(caseName)(decoded) } """) @@ -125,14 +117,14 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { initMap.append(""" { - fatalError() + return nil } """) declaration += """ - public init(jsValue: JSValue) { + public init?(from value: JSValue) { """ declaration += initMap.joined(separator: " else ") @@ -143,8 +135,9 @@ class EnumerationWithAssociatedValuesNode: TypeNode, Equatable { declaration += "\n\n" declaration += """ - public func jsValue() -> JSValue { + public var value: JSValue { jsValue() } + 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..93abd44 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/NamespaceNode.swift @@ -31,9 +31,9 @@ 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 """ declaration += members diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift index 66d8b25..5d7b468 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/ProtocolNode.swift @@ -8,15 +8,25 @@ class ProtocolNode: TypeNode, Equatable { let typeName: String var inheritsFrom: Set + 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]) { + internal init(typeName: String, inheritsFrom: Set, requiredMembers: [MemberNode], defaultImplementations: [MemberNode], kind: Kind) { self.typeName = typeName self.inheritsFrom = inheritsFrom self.requiredMembers = requiredMembers self.defaultImplementations = defaultImplementations + self.kind = kind } var isProtocol: Bool { @@ -40,7 +50,15 @@ 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 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: ", ")) { diff --git a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift index db5aea4..d3b64e7 100644 --- a/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift +++ b/Sources/WebIDL/IntermediateRepresentation/Type Nodes/TypeErasedWrapperStructNode.swift @@ -28,12 +28,14 @@ class TypeErasedWrapperStructNode: TypeNode, Equatable { // swiftlint:enable force_cast var declaration = """ - class \(swiftTypeName): JSBridgedType, \(unwrapNode(wrapped).swiftTypeName) { + class \(swiftTypeName): JSBridgedClass, \(unwrapNode(wrapped).swiftTypeName) { - let objectRef: JSObjectRef + public class var constructor: JSFunction { JSObject.global.\(wrapped.identifier).function! } - required init(objectRef: JSObjectRef) { - self.objectRef = objectRef + let jsObject: JSObject + + required init(unsafelyWrapping jsObject: JSObject) { + self.jsObject = jsObject } """ diff --git a/Sources/WebIDL/Parser/Models.swift b/Sources/WebIDL/Parser/Models.swift index 7a28045..d65edbc 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) } @@ -318,12 +319,8 @@ public struct Iterable: Equatable { public struct AsyncIterable: Equatable { public let typeWithExtendedAttributes0: TypeWithExtendedAttributes - public let typeWithExtendedAttributes1: TypeWithExtendedAttributes -} - -public enum ReturnType: Equatable { - case void - case dataType(DataType) + public let typeWithExtendedAttributes1: TypeWithExtendedAttributes? + public let argumentList: [Argument]? } public enum ReadWriteAttribute: Equatable { @@ -333,7 +330,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..b0e007b 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) @@ -982,18 +982,27 @@ public class Parser { /* AsyncIterable :: - async iterable < TypeWithExtendedAttributes , TypeWithExtendedAttributes > ; + async iterable < TypeWithExtendedAttributes OptionalType > OptionalArgumentList; */ 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)) + let optionalArgumentList = try parseOptionalArgumentList() try expect(next: .terminal(.semicolon)) - return AsyncIterable(typeWithExtendedAttributes0: typeWithExtendedAttributes0, typeWithExtendedAttributes1: typeWithExtendedAttribute1) + return AsyncIterable(typeWithExtendedAttributes0: typeWithExtendedAttributes, typeWithExtendedAttributes1: optionalType, argumentList: optionalArgumentList) + } + + func parseOptionalArgumentList() throws -> [Argument]? { + guard check(forNext: .terminal(.openingParenthesis)) else { + return nil + } + let argumentList = try parseArgumentList() + try expect(next: .terminal(.closingParenthesis)) + return argumentList } func parseReadOnlyMember(extendedAttributeList: ExtendedAttributeList) throws -> InterfaceMember { @@ -1055,7 +1064,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 +1506,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 +1518,7 @@ public class Parser { return DictionaryMember(identifier: identifier, isRequired: false, extendedAttributeList: extendedAttributeList, - dataType: dataType, + type: dataType, extendedAttributesOfDataType: nil, defaultValue: defaultValue) @@ -1585,7 +1594,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 +1606,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 +1635,8 @@ public class Parser { SingleType :: DistinguishableType any + undefined + void [removed from most recent spec] PromiseType */ @@ -1638,6 +1649,10 @@ public class Parser { tokens.removeFirst() return .any + case .terminal(.undefined), .terminal(.void): + tokens.removeFirst() + return .undefined + case let token where firstSet(for: .PromiseType).contains(token): let promise = try parsePromiseType() return .promiseType(promise) @@ -1934,29 +1949,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 +2271,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 +2328,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 +2445,7 @@ func firstSet(for symbol: NonTerminal) -> Set { case .SingleType: return union( firstSet(for: .DistinguishableType), - [.terminal(.any)], + [.terminal(.any), .terminal(.undefined), .terminal(.void)], firstSet(for: .PromiseType) ) @@ -2618,7 +2615,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..32391ce 100644 --- a/Sources/WebIDL/Tokenizer/Terminal.swift +++ b/Sources/WebIDL/Tokenizer/Terminal.swift @@ -82,7 +82,8 @@ public enum Terminal: String, Equatable, CustomStringConvertible { case unsigned = "unsigned" case short = "short" case long = "long" - case void = "void" + case void = "void" // deprecated + case undefined = "undefined" case ArrayBuffer = "ArrayBuffer" case DataView = "DataView" 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() } 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/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); 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: []) ]) } }